@whyshu/argent-engine 0.8.0-rc.8 → 0.13.27
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/MANIFEST.json +109 -43
- package/bin/runtime-install.mjs +92 -0
- package/engine/VERSION +1 -1
- package/engine/configs/billing-actions.json +30 -0
- package/engine/configs/mcp-tools.snapshot.json +47 -0
- package/engine/core/contracts/argent.contracts.json +3 -3
- package/engine/core/contracts/verbs.schema.json +64 -1
- package/engine/core/lib/account-token.mjs +37 -0
- package/engine/core/lib/contract.mjs +30 -0
- package/engine/core/lib/redact.mjs +34 -0
- package/engine/core/mcp/billing-upload.mjs +77 -0
- package/engine/core/mcp/erp-server.mjs +300 -0
- package/engine/core/mcp/gateway.mjs +333 -0
- package/engine/core/mcp/meter.mjs +101 -0
- package/engine/core/mcp/server.mjs +416 -2
- package/engine/core/mcp/vault.mjs +78 -0
- package/engine/scripts/appointment-worker.mjs +456 -35
- package/engine/scripts/appointment_grab.py +1389 -264
- package/engine/scripts/appointment_rules.py +118 -0
- package/engine/scripts/argent-timers.mjs +227 -0
- package/engine/scripts/argent-web-preflight.mjs +123 -0
- package/engine/scripts/argent-web-verify.mjs +105 -0
- package/engine/scripts/billing-upload.mjs +26 -0
- package/engine/scripts/build-doc-index.mjs +68 -0
- package/engine/scripts/build-engine-package.mjs +7 -1
- package/engine/scripts/capability-packs.lock.json +323 -300
- package/engine/scripts/check-docs-drift.mjs +51 -4
- package/engine/scripts/check-version-consistency.mjs +14 -1
- package/engine/scripts/ci-run.sh +2 -2
- package/engine/scripts/collect-intel.mjs +108 -0
- package/engine/scripts/daily-report-timer-plist.sh +18 -4
- package/engine/scripts/daily-report-timers.sh +36 -3
- package/engine/scripts/daily-report.mjs +78 -2
- package/engine/scripts/doc-status.mjs +212 -0
- package/engine/scripts/dsh-web-doctor.mjs +84 -0
- package/engine/scripts/engine-manifest.mjs +90 -0
- package/engine/scripts/engine-runtime-install.mjs +92 -0
- package/engine/scripts/erp-ui-install.mjs +127 -0
- package/engine/scripts/erp-ui-preflight.mjs +104 -0
- package/engine/scripts/erp-ui-verify.mjs +135 -0
- package/engine/scripts/flow-requirements.json +122 -99
- package/engine/scripts/full-exec-worker.mjs +251 -0
- package/engine/scripts/gen-preset-rows.mjs +1 -1
- package/engine/scripts/invoice_lip_runner.py +1 -0
- package/engine/scripts/invoice_runner.py +17 -6
- package/engine/scripts/invoice_stageb.py +21 -4
- package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
- package/engine/scripts/lib/intel-card.mjs +43 -0
- package/engine/scripts/lib/invoice_names.py +23 -0
- package/engine/scripts/lib/ml-ads-core.mjs +100 -18
- package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
- package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
- package/engine/scripts/lib/ml-category-core.mjs +120 -0
- package/engine/scripts/lib/ml-insight-core.mjs +621 -0
- package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
- package/engine/scripts/lib/ml-items.mjs +40 -0
- package/engine/scripts/lib/ml-listing-core.mjs +342 -0
- package/engine/scripts/lib/ml-market-core.mjs +774 -0
- package/engine/scripts/lib/plugin-packages.mjs +13 -0
- package/engine/scripts/lib/webdriver_ipc.py +61 -1
- package/engine/scripts/line_pack.py +196 -0
- package/engine/scripts/mcp-gateway-switch.mjs +100 -0
- package/engine/scripts/migrate-providers.mjs +3 -3
- package/engine/scripts/ml-ads-advice.mjs +140 -0
- package/engine/scripts/ml-ads.mjs +221 -0
- package/engine/scripts/ml-category-baseline.mjs +174 -0
- package/engine/scripts/ml-insight-diagnose.mjs +247 -0
- package/engine/scripts/ml-insight-run.sh +183 -0
- package/engine/scripts/ml-insight-timers.sh +224 -0
- package/engine/scripts/ml-listing-audit.mjs +170 -0
- package/engine/scripts/ml-market-matrix.mjs +84 -0
- package/engine/scripts/ml-market-snapshot.mjs +261 -0
- package/engine/scripts/ml-messages.mjs +145 -0
- package/engine/scripts/ml-oauth-setup.mjs +1 -1
- package/engine/scripts/npm-publish-argent.mjs +14 -0
- package/engine/scripts/ops-codefix-pr.mjs +87 -0
- package/engine/scripts/ops-codefix-queue.mjs +30 -0
- package/engine/scripts/ops-digest.mjs +98 -0
- package/engine/scripts/ops-verify.mjs +67 -0
- package/engine/scripts/orchestrator.py +410 -20
- package/engine/scripts/orchestrator_br.py +146 -4
- package/engine/scripts/plugin-bootcheck.mjs +50 -1
- package/engine/scripts/publish-engine.mjs +111 -0
- package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
- package/engine/scripts/skuflow_invoice_runner.py +43 -3
- package/engine/scripts/v0.9-acceptance.mjs +107 -0
- package/engine/scripts/vertical-lint.mjs +12 -1
- package/engine/scripts/web-switch.mjs +121 -0
- package/engine/scripts/wenyao_fill_template.py +52 -15
- package/engine/scripts/wenyao_run.py +2 -1
- package/engine/skills/README.md +3 -3
- package/engine/skills/bilibili-upload/SKILL.md +109 -0
- package/engine/skills/douyin-upload/SKILL.md +74 -0
- package/engine/skills/internal.json +28 -0
- package/engine/skills/kuaishou-upload/SKILL.md +109 -0
- package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
- package/engine/skills/ml-full-appointment/SKILL.md +23 -0
- package/engine/skills/ml-invoice/SKILL.md +2 -2
- package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
- package/engine/skills/ml-label-recovery/SKILL.md +43 -0
- package/engine/skills/ml-listing-audit/SKILL.md +66 -0
- package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
- package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
- package/engine/skills/ml-store-insight/SKILL.md +81 -0
- package/engine/skills/tencent-upload/SKILL.md +60 -0
- package/engine/skills/weibo-upload/SKILL.md +106 -0
- package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
- package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
- package/engine/version.mjs +1 -1
- package/engine/verticals/README.md +7 -0
- package/engine/verticals/_engine-words.baseline.txt +27 -59
- package/engine/verticals/mercadolibre/manifest.json +132 -6
- package/package.json +5 -1
|
@@ -2,9 +2,36 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* ERP 抢预约 worker(Huangwei)
|
|
4
4
|
* · 只消费 AppointmentTask,参数全部来自任务,不读 lip;
|
|
5
|
-
* · 轮询 ERP claim
|
|
6
|
-
*
|
|
7
|
-
* ·
|
|
5
|
+
* · 轮询 ERP claim(契约:POST /appointments/claim body {workerId} → data.task,
|
|
6
|
+
* 没有可领任务时 data.task = null;data.queue 是单店水位,可忽略);
|
|
7
|
+
* · 启动 appointment_grab.py 执行预约页值守循环(长跑:一个任务长期占 1 个 tab);
|
|
8
|
+
* · 用户停止通过 ERP stopRequestedAt(worker 每 5s 心跳查询)转发为 SIGTERM;
|
|
9
|
+
* · worker 负责租约/停止/收尾/并发调度。
|
|
10
|
+
*
|
|
11
|
+
* ## 2026-11-16(P1 第二步,配合 ERP 686e6df「店铺级 5 并发队列 + 优先级三档」)
|
|
12
|
+
*
|
|
13
|
+
* 一、**停机必须 complete**(否则占死店铺槽位):
|
|
14
|
+
* 旧实现收到 SIGTERM 直接 `process.exit(0)` ⇒ 已领任务不会释放 ⇒ 每店 5 个槽位耗尽后
|
|
15
|
+
* 该店再也领不到任务。现在 SIGTERM/SIGINT:
|
|
16
|
+
* ① 停止领取新任务;
|
|
17
|
+
* ② 给所有在跑的 grab 子进程发 SIGTERM(grab 自己关预约 tab 并输出 `stopped` 结果);
|
|
18
|
+
* ③ 等各任务走完 `complete`(outcome 由 grab 结果决定:`stopped`);
|
|
19
|
+
* ④ 宽限期(默认 20s)后仍未 complete 的任务(子进程没退 / complete 失败 / 已领未跑)
|
|
20
|
+
* 由 worker **直接补发** `complete{outcome:"stopped"}`,确保槽位一定释放;
|
|
21
|
+
* ⑤ 强制 SIGKILL 残留子进程后退出。
|
|
22
|
+
* 契约:POST /appointments/:id/complete body {workerId, outcome};outcome ∈
|
|
23
|
+
* succeeded/stopped/failed(停机一律 stopped)。
|
|
24
|
+
*
|
|
25
|
+
* 二、并发口径 = **按店 ≤ 5**(服务端硬保证同店 claimed+running ≤ 5;跨店不设上限):
|
|
26
|
+
* 旧实现是"全局 2"(`ARGENT_APPOINTMENT_CONCURRENCY` 默认 2、最大 5)⇒ 同一店铺 5 个预约
|
|
27
|
+
* tab 永远吃不满。现在:
|
|
28
|
+
* · `ARGENT_APPOINTMENT_STORE_CONCURRENCY` 同店上限,默认 5、最大 5(= 服务端槽位数;
|
|
29
|
+
* 调小只是保守降载,调大没有意义,服务端不会给第 6 条);
|
|
30
|
+
* · `ARGENT_APPOINTMENT_CONCURRENCY` 本 worker 总并发,默认 = 同店上限(单店场景即 5)。
|
|
31
|
+
* 跨店要更宽就把它调大(服务端跨店不限,受本机 tab/内存约束)。
|
|
32
|
+
* 每个任务独立 `appointment_grab.py` 进程 + 独立 CDP 标签页(同一店铺窗口里 5 个 tab)。
|
|
33
|
+
* 防御:若 claim 返回本店第 6 条(服务端契约异常),先**本地挂起**(不发车、也不丢任务),
|
|
34
|
+
* 等本店槽位释放再启动;挂起任务同样计入总并发预算,不会无限堆积。
|
|
8
35
|
*/
|
|
9
36
|
import fs from 'node:fs';
|
|
10
37
|
import os from 'node:os';
|
|
@@ -17,12 +44,104 @@ const HEALTH = argv.has('--health');
|
|
|
17
44
|
const CFG_PATH = process.env.ARGENT_RUNNER_CONFIG || `${process.env.DSH_HOME || `${os.homedir()}/.dsh-argent`}/argent/runner.json`;
|
|
18
45
|
const PY = process.env.ARGENT_PY || `${os.homedir()}/.dsh/argent/venv/bin/python3`;
|
|
19
46
|
const GRAB = process.env.ARGENT_APPOINTMENT_GRAB || `${os.homedir()}/.argent-dsh/scripts/appointment_grab.py`;
|
|
47
|
+
// 子进程 cwd / 数据目录:默认与旧实现一致(客户机 ~/.argent-dsh + ~/.dsh/argent),
|
|
48
|
+
// 可用 env 覆盖(夹具测试用:⛔ 测试绝不写真实数据目录)。
|
|
49
|
+
const GRAB_CWD = process.env.ARGENT_APPOINTMENT_CWD || `${os.homedir()}/.argent-dsh`;
|
|
50
|
+
const GRAB_DATA_DIR = process.env.ARGENT_DATA_DIR || `${os.homedir()}/.dsh/argent`;
|
|
20
51
|
const WORKER_ID = process.env.ARGENT_APPOINTMENT_WORKER_ID || `appointment-${os.hostname()}-${process.pid}`;
|
|
21
|
-
|
|
52
|
+
// 引擎版本文件(自更新守护,2026-11-19):客户只更新 dsh 插件 + 重启 dsh,worker 不会被重启;
|
|
53
|
+
// 引擎文件更新后本进程仍跑旧代码 ⇒ 这里检测 VERSION 变化,优雅让位(任务回队列)后退出,
|
|
54
|
+
// launchd/systemd 的 KeepAlive 会用新代码把 worker 拉起来。
|
|
55
|
+
const ENGINE_VERSION_FILE = process.env.ARGENT_ENGINE_VERSION_FILE || `${GRAB_CWD}/VERSION`;
|
|
56
|
+
const ENGINE_VERSION_POLL_MS = positiveInt(process.env.ARGENT_ENGINE_VERSION_POLL_MS, 30_000);
|
|
57
|
+
function readEngineVersion() { try { return String(fs.readFileSync(ENGINE_VERSION_FILE, 'utf8')).trim(); } catch { return ''; } }
|
|
58
|
+
let ENGINE_VERSION = readEngineVersion();
|
|
59
|
+
let RELEASE_MODE = false; // true = 停机时把任务 return 队列(自更新),而不是 complete(stopped)
|
|
60
|
+
|
|
61
|
+
function positiveInt(v, fallback) {
|
|
62
|
+
const n = Math.floor(Number(v));
|
|
63
|
+
return Number.isFinite(n) && n > 0 ? n : fallback;
|
|
64
|
+
}
|
|
65
|
+
// 队列通道(2026-11-18):manual=运营抢预约线;full=FULL 流程自动预约线。
|
|
66
|
+
// 两个通道各自独立进程(launchd 两个服务)+ 独立槽位/并发/刷新参数 ⇒ 互不占用。
|
|
67
|
+
const CHANNEL = String(process.env.ARGENT_APPOINTMENT_CHANNEL || 'manual') === 'full' ? 'full' : 'manual';
|
|
68
|
+
// 同店并发上限:服务端店铺槽位 = 5(2026-11-16 契约),worker 侧不允许更大。
|
|
69
|
+
// 2026-11-18:改为「环境变量兜底 + 服务端实时参数」——运营在 ERP 里改,worker 每 10s 拉一次。
|
|
70
|
+
let STORE_CONCURRENCY = Math.min(5, positiveInt(process.env.ARGENT_APPOINTMENT_STORE_CONCURRENCY, CHANNEL === 'full' ? 1 : 5));
|
|
71
|
+
// 总并发上限:默认 = 同店上限(单店场景等价旧"最多 5");跨店并行需要更宽时显式调大。
|
|
72
|
+
let MAX_CONCURRENCY = Math.min(50, positiveInt(process.env.ARGENT_APPOINTMENT_CONCURRENCY, CHANNEL === 'full' ? 5 : Math.max(STORE_CONCURRENCY, 5)));
|
|
73
|
+
// 抢号页面刷新抖动(秒);同样允许 ERP 实时下发(对新领取的任务生效)
|
|
74
|
+
let REFRESH_MIN_SEC = positiveInt(process.env.ARGENT_APPOINTMENT_REFRESH_MIN, 20);
|
|
75
|
+
let REFRESH_MAX_SEC = Math.max(REFRESH_MIN_SEC, positiveInt(process.env.ARGENT_APPOINTMENT_REFRESH_MAX, 40));
|
|
76
|
+
let settingsAt = 0;
|
|
77
|
+
// 停机宽限期:给在跑 grab 自己收尾(关 tab + 输出 stopped)的时间,超时由 worker 兜底 complete。
|
|
78
|
+
const SHUTDOWN_GRACE_MS = Math.max(1000, Math.min(120_000, positiveInt(process.env.ARGENT_APPOINTMENT_SHUTDOWN_GRACE_MS, 20_000)));
|
|
79
|
+
const POLL_MS = positiveInt(process.env.ARGENT_APPOINTMENT_POLL_MS, 5_000);
|
|
80
|
+
// ── 同店窗口令牌(2026-11-18,v0.11.29 起默认**并行**):
|
|
81
|
+
// 背景修正:11471「Algo salió mal」是平台大促/无号期的页面状态,**不是风控**;
|
|
82
|
+
// 技术上多标签页可以并行驱动(各 tab 独立 CDP),所以默认不做跨通道互斥。
|
|
83
|
+
// 需要"同店分时轮流驱动"时,设 ARGENT_APPOINTMENT_STORE_DRIVER=slice 开启(时间片默认 8 分钟)。
|
|
84
|
+
const STORE_DRIVER_MODE = ['slice', 'on', '1'].includes(String(process.env.ARGENT_APPOINTMENT_STORE_DRIVER || '').toLowerCase()) ? 'slice' : 'off';
|
|
85
|
+
const STORE_SLICE_MS = Math.max(60_000, positiveInt(process.env.ARGENT_APPOINTMENT_STORE_SLICE_SEC, 480) * 1000);
|
|
86
|
+
const LOCK_DIR = `${GRAB_DATA_DIR}/locks`;
|
|
87
|
+
function storeLockPath(store) {
|
|
88
|
+
const key = String(store || '').replace(/[^\w.-]+/g, '_').slice(0, 80) || 'unknown';
|
|
89
|
+
return `${LOCK_DIR}/store-driver-${key}.lock`;
|
|
90
|
+
}
|
|
91
|
+
function readStoreToken(p) { try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return null; } }
|
|
92
|
+
function pidAlive(pid) { try { process.kill(Number(pid), 0); return true; } catch { return false; } }
|
|
93
|
+
// 同进程内多个同店任务共享同一令牌(引用计数;最后一个放手才删文件)
|
|
94
|
+
const storeDriverHold = new Map();
|
|
95
|
+
function acquireStoreDriver(store) {
|
|
96
|
+
if (STORE_DRIVER_MODE !== 'slice') return { ok: true, disabled: true, token: { expiresAt: Number.MAX_SAFE_INTEGER } };
|
|
97
|
+
const key = String(store || '');
|
|
98
|
+
const p = storeLockPath(store);
|
|
99
|
+
const held = storeDriverHold.get(key) || null;
|
|
100
|
+
if (held) {
|
|
101
|
+
// 本进程已持有:同店第二个任务直接共享(跨通道互斥只针对**别的进程**)
|
|
102
|
+
held.refs += 1;
|
|
103
|
+
return { ok: true, token: held.token, path: p, shared: true };
|
|
104
|
+
}
|
|
105
|
+
try { fs.mkdirSync(LOCK_DIR, { recursive: true }); } catch { /* ignore */ }
|
|
106
|
+
const now = Date.now();
|
|
107
|
+
const cur = readStoreToken(p);
|
|
108
|
+
if (cur && Number(cur.expiresAt) > now && Number(cur.pid) !== process.pid && pidAlive(cur.pid)) {
|
|
109
|
+
return { ok: false, owner: cur, path: p };
|
|
110
|
+
}
|
|
111
|
+
const token = { pid: process.pid, channel: CHANNEL, store, acquiredAt: now, expiresAt: now + STORE_SLICE_MS };
|
|
112
|
+
try {
|
|
113
|
+
fs.writeFileSync(p, JSON.stringify(token));
|
|
114
|
+
} catch {
|
|
115
|
+
storeDriverHold.set(key, { token, refs: 1 });
|
|
116
|
+
return { ok: true, token, path: p, degraded: true };
|
|
117
|
+
}
|
|
118
|
+
storeDriverHold.set(key, { token, refs: 1 });
|
|
119
|
+
return { ok: true, token, path: p };
|
|
120
|
+
}
|
|
121
|
+
function releaseStoreDriver(store) {
|
|
122
|
+
if (STORE_DRIVER_MODE !== 'slice') return;
|
|
123
|
+
const key = String(store || '');
|
|
124
|
+
const held = storeDriverHold.get(key);
|
|
125
|
+
if (!held) return;
|
|
126
|
+
held.refs -= 1;
|
|
127
|
+
if (held.refs > 0) return;
|
|
128
|
+
storeDriverHold.delete(key);
|
|
129
|
+
const p = storeLockPath(store);
|
|
130
|
+
const cur = readStoreToken(p);
|
|
131
|
+
if (cur && Number(cur.pid) === process.pid) { try { fs.unlinkSync(p); } catch { /* ignore */ } }
|
|
132
|
+
}
|
|
133
|
+
|
|
22
134
|
|
|
23
135
|
const cfg = JSON.parse(fs.readFileSync(CFG_PATH, 'utf8'));
|
|
24
136
|
const base = `${String(cfg.serverUrl).replace(/\/+$/, '')}/api/argent/v1/tenants/${encodeURIComponent(cfg.tenantAppId)}`;
|
|
25
137
|
|
|
138
|
+
// ── 本地调度状态 ────────────────────────────────────────────────────────────
|
|
139
|
+
const active = new Map(); // taskId → { task, store, child, completed, promise }
|
|
140
|
+
const pending = []; // 已领但本店本地槽位满(防御:服务端契约保证 ≤5,正常不会进这里)
|
|
141
|
+
const storeActive = new Map();// store → 本地在跑任务数
|
|
142
|
+
let shuttingDown = false;
|
|
143
|
+
let shutdownPromise = null;
|
|
144
|
+
|
|
26
145
|
async function api(path, { method = 'GET', body } = {}) {
|
|
27
146
|
const res = await fetch(`${base}${path}`, {
|
|
28
147
|
method,
|
|
@@ -35,16 +154,40 @@ async function api(path, { method = 'GET', body } = {}) {
|
|
|
35
154
|
return json.data;
|
|
36
155
|
}
|
|
37
156
|
|
|
38
|
-
|
|
157
|
+
/** 完成一个任务(停机路径与正常路径共用)。重试 3 次:complete 失败 = 槽位没释放。 */
|
|
158
|
+
async function completeTask(task, body, attempts = 3) {
|
|
159
|
+
let lastErr = null;
|
|
160
|
+
for (let i = 0; i < attempts; i++) {
|
|
161
|
+
try {
|
|
162
|
+
return await api(`/appointments/${encodeURIComponent(task._id)}/complete`, {
|
|
163
|
+
method: 'POST', body: { workerId: WORKER_ID, ...body },
|
|
164
|
+
});
|
|
165
|
+
} catch (e) {
|
|
166
|
+
lastErr = e;
|
|
167
|
+
if (i < attempts - 1) await sleep(1000 * (i + 1));
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
throw lastErr;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function runGrab(task, onEvent = null, rec = null) {
|
|
39
174
|
return new Promise((resolve) => {
|
|
40
175
|
const args = [GRAB,
|
|
41
176
|
'--task-json', JSON.stringify(task),
|
|
42
177
|
'--cdp-hint', process.env.ARGENT_APPOINTMENT_CDP_HINT || '',
|
|
178
|
+
'--refresh-min', String(REFRESH_MIN_SEC),
|
|
179
|
+
'--refresh-max', String(REFRESH_MAX_SEC),
|
|
43
180
|
];
|
|
44
181
|
const child = spawn(PY, args, {
|
|
45
|
-
cwd:
|
|
182
|
+
cwd: GRAB_CWD,
|
|
183
|
+
env: {
|
|
184
|
+
...process.env,
|
|
185
|
+
ARGENT_DATA_DIR: GRAB_DATA_DIR,
|
|
186
|
+
PATH: `${os.homedir()}/.local/node/bin:${os.homedir()}/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin`,
|
|
187
|
+
},
|
|
46
188
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
47
189
|
});
|
|
190
|
+
if (rec) rec.child = child;
|
|
48
191
|
let stdout = ''; let stderr = ''; let lineBuf = '';
|
|
49
192
|
child.stdout.on('data', (d) => {
|
|
50
193
|
const text = String(d); stdout += text; console.log(text.trimEnd());
|
|
@@ -58,6 +201,7 @@ function runGrab(task, onEvent = null) {
|
|
|
58
201
|
});
|
|
59
202
|
child.stderr.on('data', (d) => { stderr += d; console.error(String(d).trimEnd()); });
|
|
60
203
|
const heartbeat = setInterval(async () => {
|
|
204
|
+
if (shuttingDown) return;
|
|
61
205
|
try {
|
|
62
206
|
const d = await api(`/appointments/${encodeURIComponent(task._id)}/state`, { method: 'GET' });
|
|
63
207
|
if (d?.task?.stopRequestedAt) {
|
|
@@ -66,18 +210,62 @@ function runGrab(task, onEvent = null) {
|
|
|
66
210
|
}
|
|
67
211
|
} catch { /* ignore transient */ }
|
|
68
212
|
}, 5_000);
|
|
69
|
-
|
|
70
|
-
|
|
213
|
+
const finish = (patch) => {
|
|
214
|
+
clearInterval(heartbeat);
|
|
215
|
+
if (rec && rec.child === child) rec.child = null;
|
|
216
|
+
resolve(patch);
|
|
217
|
+
};
|
|
218
|
+
child.on('error', (e) => finish({ code: -1, stdout, stderr: `${stderr}\n${e.message}` }));
|
|
219
|
+
child.on('exit', (code, signal) => finish({ code, signal, stdout, stderr }));
|
|
71
220
|
});
|
|
72
221
|
}
|
|
73
222
|
|
|
223
|
+
/** 从服务端拉「抢预约运行参数」(运营在 ERP 里实时调;失败保留旧值) */
|
|
224
|
+
async function refreshRemoteSettings(force = false) {
|
|
225
|
+
if (!force && Date.now() - settingsAt < 10_000) return;
|
|
226
|
+
settingsAt = Date.now();
|
|
227
|
+
try {
|
|
228
|
+
const d = await api(`/appointments/worker-settings?channel=${encodeURIComponent(CHANNEL)}`);
|
|
229
|
+
const st = (d && d.settings) || {};
|
|
230
|
+
const sc = Math.min(5, Math.max(1, Math.round(Number(st.storeConcurrency) || STORE_CONCURRENCY)));
|
|
231
|
+
const mc = Math.min(50, Math.max(1, Math.round(Number(st.concurrency) || MAX_CONCURRENCY)));
|
|
232
|
+
const rmin = Math.max(5, Math.round(Number(st.refreshMinSec) || REFRESH_MIN_SEC));
|
|
233
|
+
const rmax = Math.max(rmin, Math.round(Number(st.refreshMaxSec) || REFRESH_MAX_SEC));
|
|
234
|
+
const changed = sc !== STORE_CONCURRENCY || mc !== MAX_CONCURRENCY || rmin !== REFRESH_MIN_SEC || rmax !== REFRESH_MAX_SEC;
|
|
235
|
+
STORE_CONCURRENCY = sc; MAX_CONCURRENCY = mc; REFRESH_MIN_SEC = rmin; REFRESH_MAX_SEC = rmax;
|
|
236
|
+
if (changed) {
|
|
237
|
+
console.log(JSON.stringify({ event: 'settings.updated', storeConcurrency: sc, concurrency: mc, refreshMinSec: rmin, refreshMaxSec: rmax }));
|
|
238
|
+
}
|
|
239
|
+
} catch { /* 参数拉取失败不影响主流程,沿用旧值 */ }
|
|
240
|
+
}
|
|
241
|
+
|
|
74
242
|
async function claimTask() {
|
|
75
|
-
const d = await api('/appointments/claim', { method: 'POST', body: { workerId: WORKER_ID } });
|
|
243
|
+
const d = await api('/appointments/claim', { method: 'POST', body: { workerId: WORKER_ID, channel: CHANNEL } });
|
|
244
|
+
// 契约(2026-11-16):data.task 为 null = 当前没有可领任务(不是 404);data.queue 可忽略
|
|
76
245
|
return d?.task || null;
|
|
77
246
|
}
|
|
78
247
|
|
|
79
|
-
async function runTask(task) {
|
|
80
|
-
console.log(JSON.stringify({ event: 'claimed', id: task._id, store: task.store, sku: task.sku, shipmentNo: task.shipmentNo, from: task.dateFrom, to: task.dateTo, concurrency: MAX_CONCURRENCY }));
|
|
248
|
+
async function runTask(task, rec = null) {
|
|
249
|
+
console.log(JSON.stringify({ event: 'claimed', id: task._id, store: task.store, sku: task.sku, shipmentNo: task.shipmentNo, from: task.dateFrom, to: task.dateTo, concurrency: MAX_CONCURRENCY, storeConcurrency: STORE_CONCURRENCY }));
|
|
250
|
+
// 同店窗口令牌:另一通道正在驱动同一紫鸟窗口 ⇒ 让位(归还队列,进度保留,不算失败)
|
|
251
|
+
const driver = acquireStoreDriver(task.store);
|
|
252
|
+
if (!driver.ok) {
|
|
253
|
+
const owner = (driver.owner && driver.owner.channel) || '另一通道';
|
|
254
|
+
console.log(JSON.stringify({ event: 'yielded', id: task._id, store: task.store, reason: 'store-driver-busy', owner }));
|
|
255
|
+
try {
|
|
256
|
+
await api(`/appointments/${encodeURIComponent(task._id)}/release`, {
|
|
257
|
+
method: 'POST', body: { workerId: WORKER_ID, reason: 'yield-store-driver', allowStarted: true },
|
|
258
|
+
});
|
|
259
|
+
} catch (e) { console.error(JSON.stringify({ event: 'yield.release.error', id: task._id, message: e.message })); }
|
|
260
|
+
return 'yielded';
|
|
261
|
+
}
|
|
262
|
+
if (rec) rec.driverHeld = true;
|
|
263
|
+
const sliceTimer = STORE_DRIVER_MODE === 'slice' ? setTimeout(() => {
|
|
264
|
+
if (!rec || rec.completed) return;
|
|
265
|
+
rec.yielding = true;
|
|
266
|
+
console.log(JSON.stringify({ event: 'yield-slice', id: task._id, store: task.store, sliceSec: Math.round(STORE_SLICE_MS / 1000) }));
|
|
267
|
+
if (rec.child) { try { rec.child.kill('SIGTERM'); } catch { /* ignore */ } }
|
|
268
|
+
}, STORE_SLICE_MS) : null;
|
|
81
269
|
// 串行发送:首张卡必须先完成(服务端回填 cardMessageId),后续 progress 才更新同一张卡。
|
|
82
270
|
// 旧实现 fire-and-forget,首批并发 progress 会在 cardMessageId 落库前各自发卡 ⇒ 重复“进行中”卡片。
|
|
83
271
|
let progressChain = Promise.resolve();
|
|
@@ -94,56 +282,289 @@ async function runTask(task) {
|
|
|
94
282
|
if (evt.event === 'cycle' || evt.event === 'progress') {
|
|
95
283
|
sendProgress(evt.cycle || 0, evt.dateStates || {}, 'cycle', evt.checks || 0);
|
|
96
284
|
}
|
|
97
|
-
|
|
285
|
+
// 令牌过期(另一通道已接班)/ 到时间片 ⇒ 让位
|
|
286
|
+
if (rec && !rec.yielding && Date.now() > driver.token.expiresAt) {
|
|
287
|
+
rec.yielding = true;
|
|
288
|
+
console.log(JSON.stringify({ event: 'yield-slice', id: task._id, store: task.store, reason: 'token-expired' }));
|
|
289
|
+
if (rec.child) { try { rec.child.kill('SIGTERM'); } catch { /* ignore */ } }
|
|
290
|
+
}
|
|
291
|
+
}, rec);
|
|
292
|
+
clearTimeout(sliceTimer);
|
|
98
293
|
let result = {};
|
|
99
294
|
for (const line of String(r.stdout || '').trim().split('\n').reverse()) {
|
|
100
295
|
try { const j = JSON.parse(line); if (j && (j.status || j.outcome)) { result = j; break; } } catch { /* not json */ }
|
|
101
296
|
}
|
|
102
297
|
if (!result.status && (r.signal === 'SIGTERM' || r.code === 143)) result.status = 'stopped';
|
|
298
|
+
if (shuttingDown && !result.status) result.status = 'stopped';
|
|
299
|
+
// 时间片让位:不判失败/停止,直接归还队列(进度已落库,下次接着抢)
|
|
300
|
+
if (rec && rec.yielding && !shuttingDown) {
|
|
301
|
+
try {
|
|
302
|
+
await api(`/appointments/${encodeURIComponent(task._id)}/release`, {
|
|
303
|
+
method: 'POST', body: { workerId: WORKER_ID, reason: 'yield-slice', allowStarted: true },
|
|
304
|
+
});
|
|
305
|
+
console.log(JSON.stringify({ event: 'yielded', id: task._id, store: task.store, reason: 'slice-end' }));
|
|
306
|
+
} catch (e) {
|
|
307
|
+
console.error(JSON.stringify({ event: 'yield.release.error', id: task._id, message: e.message }));
|
|
308
|
+
}
|
|
309
|
+
releaseStoreDriver(task.store);
|
|
310
|
+
if (rec) rec.completed = true;
|
|
311
|
+
return 'yielded';
|
|
312
|
+
}
|
|
313
|
+
// 引擎自更新:把任务归还队列(保留进度),⛔ 不判 stopped/failed
|
|
314
|
+
if (RELEASE_MODE) {
|
|
315
|
+
try {
|
|
316
|
+
await api(`/appointments/${encodeURIComponent(task._id)}/release`, {
|
|
317
|
+
method: 'POST', body: { workerId: WORKER_ID, reason: 'engine-updated', allowStarted: true },
|
|
318
|
+
});
|
|
319
|
+
console.log(JSON.stringify({ event: 'released', id: task._id, store: task.store, reason: 'engine-updated' }));
|
|
320
|
+
} catch (e) {
|
|
321
|
+
console.error(JSON.stringify({ event: 'release.error', id: task._id, reason: 'engine-updated', message: e.message }));
|
|
322
|
+
}
|
|
323
|
+
releaseStoreDriver(task.store);
|
|
324
|
+
if (rec) rec.completed = true;
|
|
325
|
+
return 'released';
|
|
326
|
+
}
|
|
103
327
|
const outcome = result.status === 'booked' ? 'succeeded' : result.status === 'stopped' ? 'stopped' : 'failed';
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
328
|
+
try {
|
|
329
|
+
await completeTask(task, {
|
|
330
|
+
outcome,
|
|
331
|
+
summary: result.summary || r.stderr.slice(-800) || r.stdout.slice(-800),
|
|
332
|
+
resultDate: result.date || '',
|
|
333
|
+
existingDate: result.existingDate || '',
|
|
334
|
+
existingSlot: result.existingSlot || '',
|
|
335
|
+
resultSlot: result.slot || '',
|
|
336
|
+
dateStates: result.dateStates || {},
|
|
337
|
+
});
|
|
338
|
+
if (rec) rec.completed = true;
|
|
339
|
+
} catch (e) {
|
|
340
|
+
// complete 失败 = 槽位没释放:必须让人看见(任务保持 claimed,下次停机兜底/服务端租约兜底)
|
|
341
|
+
console.error(JSON.stringify({ event: 'complete.error', id: task._id, outcome, message: e.message }));
|
|
342
|
+
releaseStoreDriver(task.store);
|
|
343
|
+
throw e;
|
|
344
|
+
}
|
|
108
345
|
console.log(JSON.stringify({ event: 'completed', id: task._id, outcome, date: result.date || '', slot: result.slot || '' }));
|
|
346
|
+
releaseStoreDriver(task.store);
|
|
109
347
|
return outcome;
|
|
110
348
|
}
|
|
111
349
|
|
|
350
|
+
function storeRunning(store) {
|
|
351
|
+
return storeActive.get(String(store || '')) || 0;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function launchTask(task) {
|
|
355
|
+
const id = String(task._id);
|
|
356
|
+
const store = String(task.store || '');
|
|
357
|
+
const rec = { id, store, task, child: null, completed: false };
|
|
358
|
+
storeActive.set(store, storeRunning(store) + 1);
|
|
359
|
+
active.set(id, rec);
|
|
360
|
+
rec.promise = runTask(task, rec)
|
|
361
|
+
.catch(async (e) => {
|
|
362
|
+
// 2026-11-18:runTask 早期异常(发进度/开子进程前)会把任务留在 claimed 变「僵尸任务」:
|
|
363
|
+
// ERP 显示进行中、实际没有 grab 进程/标签页。这里兜底把任务归还队列,避免槽位被白占。
|
|
364
|
+
console.error(JSON.stringify({ event: 'task.error', id, store, message: e.message }));
|
|
365
|
+
try {
|
|
366
|
+
await api(`/appointments/${encodeURIComponent(id)}/release`, {
|
|
367
|
+
method: 'POST', body: { workerId: WORKER_ID, reason: 'worker-error', allowStarted: true },
|
|
368
|
+
});
|
|
369
|
+
console.log(JSON.stringify({ event: 'released', id, store, reason: 'worker-error' }));
|
|
370
|
+
} catch (e2) {
|
|
371
|
+
console.error(JSON.stringify({ event: 'release.error', id, message: e2.message }));
|
|
372
|
+
}
|
|
373
|
+
})
|
|
374
|
+
.finally(() => {
|
|
375
|
+
active.delete(id);
|
|
376
|
+
storeActive.set(store, Math.max(0, storeRunning(store) - 1));
|
|
377
|
+
pumpPending();
|
|
378
|
+
});
|
|
379
|
+
return rec;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** 把挂起任务中「本店已有空位」的启动起来(防御路径 + 任务结束后补位共用)。 */
|
|
383
|
+
function pumpPending() {
|
|
384
|
+
if (shuttingDown) return;
|
|
385
|
+
for (let i = 0; i < pending.length;) {
|
|
386
|
+
const item = pending[i];
|
|
387
|
+
// 从 pending 挪到 active 不增加总并发(总预算在 claimAndStart 里按 active+pending 计),
|
|
388
|
+
// 这里只看本店是否已有空位。
|
|
389
|
+
if (storeRunning(item.store) < STORE_CONCURRENCY) {
|
|
390
|
+
pending.splice(i, 1);
|
|
391
|
+
launchTask(item.task);
|
|
392
|
+
} else {
|
|
393
|
+
i += 1;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** 领任务并启动,直到没有任务可领 / 总并发预算用完 / 正在停机。 */
|
|
399
|
+
let storeBusyStreak = 0;
|
|
400
|
+
let claimPausedUntil = 0; // 连续店满后暂停领取的截止时间(修 release 空转)
|
|
401
|
+
|
|
402
|
+
async function claimAndStart() {
|
|
403
|
+
await refreshRemoteSettings(); // 运营实时调参:每 10s 最多拉一次
|
|
404
|
+
if (Date.now() < claimPausedUntil) return; // 空转退避中:定时器再叫也不领
|
|
405
|
+
pumpPending();
|
|
406
|
+
storeBusyStreak = 0;
|
|
407
|
+
while (!shuttingDown && active.size + pending.length < MAX_CONCURRENCY) {
|
|
408
|
+
let task;
|
|
409
|
+
try {
|
|
410
|
+
task = await claimTask();
|
|
411
|
+
} catch (e) {
|
|
412
|
+
console.error(JSON.stringify({ event: 'worker.error', message: e.message }));
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
if (!task) return;
|
|
416
|
+
if (shuttingDown) {
|
|
417
|
+
// 停机竞争窗口:claim 请求在途时收到 SIGTERM ⇒ 这条已领任务不在 shutdown 的快照里,
|
|
418
|
+
// 必须在这里立刻 complete(stopped),否则进程退出后它占着店铺槽位没人释放。
|
|
419
|
+
try {
|
|
420
|
+
await completeTask(task, { outcome: 'stopped', summary: 'worker 停机(SIGTERM/SIGINT)释放店铺槽位' });
|
|
421
|
+
} catch (e) {
|
|
422
|
+
console.error(JSON.stringify({ event: 'complete.error', id: task._id, phase: 'shutdown-claim-race', message: e.message }));
|
|
423
|
+
}
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
const store = String(task.store || '');
|
|
427
|
+
if (storeRunning(store) >= STORE_CONCURRENCY) {
|
|
428
|
+
// 2026-11-17:本店已满时**归还服务端队列**(不占槽位、不浪费排队顺序),
|
|
429
|
+
// 而不是 hold 住(旧实现会把 claimed 任务攥在本地 pending 里,槽位白占、UI 显示"进行中"却不跑)。
|
|
430
|
+
try {
|
|
431
|
+
await api(`/appointments/${encodeURIComponent(task._id)}/release`, {
|
|
432
|
+
// allowStarted:任务可能已带历史进度(attempts/progressChecks>0),不限“未开始”才能归还;
|
|
433
|
+
// 否则 release 失败 ⇒ pending 里攥着 claimed 任务 = ERP 显示进行中却没在跑(僵尸任务)。
|
|
434
|
+
method: 'POST', body: { workerId: WORKER_ID, reason: 'store-busy', allowStarted: true },
|
|
435
|
+
});
|
|
436
|
+
console.log(JSON.stringify({ event: 'released', id: task._id, store, running: storeRunning(store) }));
|
|
437
|
+
} catch (e) {
|
|
438
|
+
console.error(JSON.stringify({ event: 'release.error', id: task._id, message: e.message }));
|
|
439
|
+
// 归还失败也不能攥着:直接 complete(stopped) 释放槽位(任务可由运营重新发起)
|
|
440
|
+
try {
|
|
441
|
+
await completeTask(task, { outcome: 'stopped', summary: '同店并发已满,归还队列失败,改为停止释放槽位' });
|
|
442
|
+
console.log(JSON.stringify({ event: 'completed', id: task._id, outcome: 'stopped', reason: 'store-busy-release-failed' }));
|
|
443
|
+
} catch (e2) {
|
|
444
|
+
console.error(JSON.stringify({ event: 'complete.error', id: task._id, phase: 'store-busy', message: e2.message }));
|
|
445
|
+
pending.push({ task, store }); // 最后兜底才本地挂起(不丢任务)
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
storeBusyStreak += 1;
|
|
449
|
+
// 连续多次都是"同店满" ⇒ 店里没空位,继续领只会 claim/release 空转
|
|
450
|
+
if (storeBusyStreak >= 3) {
|
|
451
|
+
claimPausedUntil = Date.now() + 45_000;
|
|
452
|
+
console.log(JSON.stringify({ event: 'claim.paused', seconds: 45, reason: 'store-busy' }));
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
storeBusyStreak = 0;
|
|
458
|
+
launchTask(task);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// ── 停机:必须把在跑/已领任务 complete(stopped) 再退出(否则占死店铺槽位)──────
|
|
463
|
+
async function shutdown(signal) {
|
|
464
|
+
if (shutdownPromise) return shutdownPromise;
|
|
465
|
+
shuttingDown = true;
|
|
466
|
+
RELEASE_MODE = signal === 'engine-updated';
|
|
467
|
+
const running = [...active.values()];
|
|
468
|
+
const heldTasks = pending.splice(0).map((it) => it.task);
|
|
469
|
+
console.error(JSON.stringify({
|
|
470
|
+
event: 'worker.stopping', signal, running: running.length, held: heldTasks.length,
|
|
471
|
+
graceMs: SHUTDOWN_GRACE_MS,
|
|
472
|
+
}));
|
|
473
|
+
// ① 给在跑 grab 发 SIGTERM:grab 会关自己的预约 tab 并输出 stopped 结果
|
|
474
|
+
for (const rec of running) {
|
|
475
|
+
try { rec.child?.kill('SIGTERM'); } catch { /* 子进程可能已退出 */ }
|
|
476
|
+
}
|
|
477
|
+
// ② 等在跑任务各自走完 complete(宽限期内)
|
|
478
|
+
if (running.length) {
|
|
479
|
+
await Promise.race([
|
|
480
|
+
Promise.allSettled(running.map((rec) => rec.promise)),
|
|
481
|
+
sleep(SHUTDOWN_GRACE_MS),
|
|
482
|
+
]);
|
|
483
|
+
}
|
|
484
|
+
// ③ 兜底:仍没 complete 的(子进程没退/complete 失败/已领未跑)直接补发 complete(stopped)
|
|
485
|
+
// 并行发(停机窗口有限:串行 N 条 × 3 次重试可能超过 launchd/systemd 的 SIGKILL 时间)
|
|
486
|
+
const leftovers = [...running.filter((rec) => !rec.completed).map((rec) => rec.task), ...heldTasks];
|
|
487
|
+
const ret = await Promise.allSettled(leftovers.map((task) => (RELEASE_MODE
|
|
488
|
+
? api(`/appointments/${encodeURIComponent(task._id)}/release`, {
|
|
489
|
+
method: 'POST', body: { workerId: WORKER_ID, reason: 'engine-updated', allowStarted: true },
|
|
490
|
+
})
|
|
491
|
+
: completeTask(task, {
|
|
492
|
+
outcome: 'stopped',
|
|
493
|
+
summary: 'worker 停机(SIGTERM/SIGINT)释放店铺槽位',
|
|
494
|
+
}, 5))));
|
|
495
|
+
let released = 0;
|
|
496
|
+
ret.forEach((r, i) => {
|
|
497
|
+
if (r.status === 'fulfilled') { released += 1; return; }
|
|
498
|
+
console.error(JSON.stringify({
|
|
499
|
+
event: 'complete.error', id: leftovers[i]?._id, phase: 'shutdown',
|
|
500
|
+
message: String(r.reason?.message || r.reason),
|
|
501
|
+
}));
|
|
502
|
+
});
|
|
503
|
+
// ④ 残留子进程强杀(仍不退的),然后退出
|
|
504
|
+
for (const rec of active.values()) {
|
|
505
|
+
try { rec.child?.kill('SIGKILL'); } catch { /* ignore */ }
|
|
506
|
+
}
|
|
507
|
+
console.error(JSON.stringify({
|
|
508
|
+
event: 'worker.stopped', signal, released, stillActive: active.size, completedByWorker: running.length,
|
|
509
|
+
}));
|
|
510
|
+
process.exit(0);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function installSignalHandlers() {
|
|
514
|
+
for (const sig of ['SIGTERM', 'SIGINT']) {
|
|
515
|
+
process.on(sig, () => {
|
|
516
|
+
if (shutdownPromise) return;
|
|
517
|
+
shutdownPromise = shutdown(sig);
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
// 进程一启动就接管信号:ONCE 模式(单个任务)同样要保证停机释放槽位
|
|
522
|
+
installSignalHandlers();
|
|
523
|
+
|
|
524
|
+
function startEngineVersionWatch() {
|
|
525
|
+
if (!ENGINE_VERSION_POLL_MS || ENGINE_VERSION_POLL_MS <= 0) return;
|
|
526
|
+
setInterval(() => {
|
|
527
|
+
const next = readEngineVersion();
|
|
528
|
+
if (!next || next === ENGINE_VERSION) return;
|
|
529
|
+
console.error(JSON.stringify({ event: 'worker.update-detected', from: ENGINE_VERSION, to: next }));
|
|
530
|
+
ENGINE_VERSION = next;
|
|
531
|
+
shutdown('engine-updated').catch((e) => console.error(JSON.stringify({ event: 'worker.update-restart.error', message: String(e?.message || e) })));
|
|
532
|
+
}, ENGINE_VERSION_POLL_MS).unref?.();
|
|
533
|
+
}
|
|
534
|
+
|
|
112
535
|
async function runOnce() {
|
|
113
536
|
const task = await claimTask();
|
|
114
537
|
if (!task) return false;
|
|
115
|
-
|
|
538
|
+
launchTask(task);
|
|
539
|
+
await Promise.allSettled([...active.values()].map((rec) => rec.promise));
|
|
116
540
|
return true;
|
|
117
541
|
}
|
|
118
542
|
|
|
119
543
|
async function runConcurrent() {
|
|
120
|
-
const active = new Map();
|
|
121
|
-
process.on('SIGTERM', () => {
|
|
122
|
-
for (const h of active.values()) { try { h.child?.kill('SIGTERM'); } catch { /* ignore */ } }
|
|
123
|
-
process.exit(0);
|
|
124
|
-
});
|
|
125
544
|
for (;;) {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
const id = String(task._id);
|
|
131
|
-
const p = runTask(task)
|
|
132
|
-
.catch((e) => console.error(JSON.stringify({ event: 'task.error', id, message: e.message })))
|
|
133
|
-
.finally(() => active.delete(id));
|
|
134
|
-
active.set(id, p);
|
|
545
|
+
if (shuttingDown) {
|
|
546
|
+
if (!active.size) return;
|
|
547
|
+
await sleep(POLL_MS);
|
|
548
|
+
continue;
|
|
135
549
|
}
|
|
136
|
-
|
|
137
|
-
|
|
550
|
+
await claimAndStart();
|
|
551
|
+
if (!active.size) { await sleep(POLL_MS); continue; }
|
|
552
|
+
await Promise.race([...[...active.values()].map((rec) => rec.promise), sleep(POLL_MS)]);
|
|
138
553
|
}
|
|
139
554
|
}
|
|
140
555
|
|
|
141
|
-
|
|
142
556
|
async function main() {
|
|
143
557
|
if (HEALTH) {
|
|
144
558
|
try { await api('/appointments?limit=1'); console.log(JSON.stringify({ ok: true, workerId: WORKER_ID })); process.exit(0); } catch (e) { console.error(e.message); process.exit(1); }
|
|
145
559
|
}
|
|
146
|
-
console.log(JSON.stringify({
|
|
560
|
+
console.log(JSON.stringify({
|
|
561
|
+
event: 'worker.start', workerId: WORKER_ID, channel: CHANNEL, storeDriver: STORE_DRIVER_MODE, cfg: CFG_PATH, grab: GRAB,
|
|
562
|
+
concurrency: MAX_CONCURRENCY, storeConcurrency: STORE_CONCURRENCY,
|
|
563
|
+
refreshMinSec: REFRESH_MIN_SEC, refreshMaxSec: REFRESH_MAX_SEC,
|
|
564
|
+
shutdownGraceMs: SHUTDOWN_GRACE_MS,
|
|
565
|
+
engineVersion: ENGINE_VERSION,
|
|
566
|
+
}));
|
|
567
|
+
if (!ONCE) startEngineVersionWatch();
|
|
147
568
|
if (ONCE) {
|
|
148
569
|
try { await runOnce(); } catch (e) { console.error(JSON.stringify({ event: 'worker.error', message: e.message })); }
|
|
149
570
|
return;
|