taskboard-workbench 0.3.2 → 0.3.3
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 +43 -0
- package/index.js +73 -7
- package/package.json +1 -1
- package/skills/taskboard-flow/SKILL.md +1 -1
- package/skills/taskboard-flow/references/steps/S5.md +21 -1
- package/src/core/config.mjs +12 -3
- package/src/core/data-dir-hint.mjs +52 -0
- package/src/core/errors.mjs +9 -0
- package/src/core/evidence.mjs +28 -0
- package/src/core/executor.mjs +27 -7
- package/src/core/executors.mjs +279 -0
- package/src/core/instance-lease.mjs +113 -0
- package/src/core/store.mjs +182 -15
- package/src/core/verify.mjs +27 -0
- package/src/mcp/server.mjs +19 -6
- package/src/mcp/tools.mjs +96 -5
- package/src/server/api.mjs +153 -9
- package/web/app.js +468 -23
- package/web/tokens.css +29 -0
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* executors.mjs —— **执行者注册表(唯一真源)**。
|
|
3
|
+
*
|
|
4
|
+
* 背景(卡 `-238` / 需求 `R174`,2026-11-10 真机批注):「用哪个执行者跑这一张卡」当时只能靠
|
|
5
|
+
* **项目级** `teamTemplate.roles[].executor` 决定 —— 人在卡片上看到的只有一句「交给 CLI 执行器执行」,
|
|
6
|
+
* 想换执行者得先去配置页改项目设置、再回来重新点,且换不了「这一次」。本模块把执行者做成**一张表**:
|
|
7
|
+
* 前端只渲染这张表给的 `id`,服务端只在收到 `id` 时按表解析 —— **两边都不再散落执行者知识**。
|
|
8
|
+
*
|
|
9
|
+
* 四条通道的真实能力(2026-11-10 逐条读 `--help` 实测,**不猜**):
|
|
10
|
+
* · `team` —— 团队派发(`POST /api/teams`),执行者由项目 `executionTeam` 与 roles 决定
|
|
11
|
+
* · `host:dsh` —— 宿主会话执行(`POST /api/tasks/:ref/execute`)。**`dsh` 没有 oneshot 入口**
|
|
12
|
+
* (`dsh [--profile] <name>` 是启动宿主、`dsh plugin` 是管插件),
|
|
13
|
+
* 故它**只能**映射到既有的宿主会话通道,**不伪造一个 `dsh -p` 出来**
|
|
14
|
+
* · `cli:claude` —— `claude -p --permission-mode acceptEdits --allowedTools … --add-dir <cwd>`(既有通道)
|
|
15
|
+
* · `cli:codex` —— `codex exec -s workspace-write -C <cwd> -`(prompt 走 stdin,`-` 显式声明)
|
|
16
|
+
* · `cli:hermes` —— `hermes -z <prompt> --in <cwd> --yolo`(`-z` 一次一答、`--yolo` 跳审批;
|
|
17
|
+
* **prompt 走 argv**——该 CLI 的单次入口不吃 stdin)
|
|
18
|
+
*
|
|
19
|
+
* 纪律:
|
|
20
|
+
* · 纯 Node 内置模块,零依赖;探测可注入(`detect` / `now`),便于单测造「未安装」。
|
|
21
|
+
* · **不自己 spawn 干活**:参数只负责**描述**怎么调用,真正 spawn 仍在 `executor.mjs`(一处执行)。
|
|
22
|
+
* · `forbiddenExecutors` **优先级最高**:项目禁掉的执行者,按卡选也一律不可用。
|
|
23
|
+
*/
|
|
24
|
+
import { execFile } from "node:child_process";
|
|
25
|
+
import { accessSync, constants as FS, statSync } from "node:fs";
|
|
26
|
+
import { homedir } from "node:os";
|
|
27
|
+
import { delimiter, join } from "node:path";
|
|
28
|
+
|
|
29
|
+
// 参数真源复用既有 claude 通道(含 `teamTemplate.engineer.args` 整体覆盖语义)——**不抄第二份**。
|
|
30
|
+
import { cliArgsFor } from "./executor.mjs";
|
|
31
|
+
|
|
32
|
+
/** 执行者形态:团队派发 / 宿主会话 / CLI 子进程。 */
|
|
33
|
+
export const EXECUTOR_KINDS = Object.freeze({
|
|
34
|
+
TEAM: "team",
|
|
35
|
+
HOST_SESSION: "host-session",
|
|
36
|
+
CLI: "cli",
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
/** 探测缓存 TTL:60s(同一台机器上「装没装」不会秒级变化,但人装完不该等重启)。 */
|
|
40
|
+
export const DETECT_TTL_MS = 60 * 1000;
|
|
41
|
+
/**
|
|
42
|
+
* `--version` 探测超时:2s。
|
|
43
|
+
*
|
|
44
|
+
* 为什么只有 2s 且**并行**:真机实测 `hermes --version` **不退出**(超过 10s 仍在跑,只能杀掉)——
|
|
45
|
+
* 串行 + 长超时会让「打开抽屉」卡住好几秒去等一个**只用于 tooltip** 的字段。
|
|
46
|
+
* 版本拿不到就是 `null`,绝不为它拖慢接口。
|
|
47
|
+
*/
|
|
48
|
+
export const VERSION_TIMEOUT_MS = 2000;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 探测路径(**只用于探测与取绝对路径,不改 `process.env.PATH`**)。
|
|
52
|
+
*
|
|
53
|
+
* 为什么不能只按 `PATH`:宿主(`dsh web`)常由 launchd 拉起,`PATH` 往往只有
|
|
54
|
+
* `/usr/bin:/bin:/usr/sbin:/sbin` —— 用户在终端里跑得好好的 `claude` / `codex` / `hermes`
|
|
55
|
+
* 一个都不在。只按 PATH 判会把「装了」误报成「没装」,界面上就是**一排全灰的图标**
|
|
56
|
+
* (人只会以为功能坏了,不会想到是 PATH 不全)。
|
|
57
|
+
*/
|
|
58
|
+
export function executorSearchDirs({ env = process.env } = {}) {
|
|
59
|
+
const dirs = new Set();
|
|
60
|
+
const push = (value) => {
|
|
61
|
+
const dir = String(value ?? "").trim();
|
|
62
|
+
if (dir) dirs.add(dir);
|
|
63
|
+
};
|
|
64
|
+
for (const dir of String(env?.PATH ?? "").split(delimiter)) push(dir);
|
|
65
|
+
const home = String(env?.HOME ?? "") || homedir();
|
|
66
|
+
push(join(home, ".npm-global", "bin"));
|
|
67
|
+
push(join(home, ".local", "bin"));
|
|
68
|
+
push(join(home, ".bun", "bin"));
|
|
69
|
+
push(join(home, ".cargo", "bin"));
|
|
70
|
+
push("/opt/homebrew/bin");
|
|
71
|
+
push("/usr/local/bin");
|
|
72
|
+
push("/usr/bin");
|
|
73
|
+
return [...dirs];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const detectCache = new Map();
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 探测某个命令是否可执行,并给出**绝对路径**(拿到就优先用它 spawn:launchd 的 PATH 问题就绕开了)。
|
|
80
|
+
* @returns {{ installed: boolean, binPath: string|null, searched: string[] }}
|
|
81
|
+
*/
|
|
82
|
+
export function detectBinary(command, { env = process.env, now = () => Date.now(), ttlMs = DETECT_TTL_MS, fresh = false, searchDirs = null } = {}) {
|
|
83
|
+
const name = String(command ?? "").trim();
|
|
84
|
+
if (!name) return { installed: false, binPath: null, searched: [] };
|
|
85
|
+
const dirs = searchDirs ?? executorSearchDirs({ env });
|
|
86
|
+
const key = `${name}\u0000${dirs.join("\u0000")}`;
|
|
87
|
+
const hit = detectCache.get(key);
|
|
88
|
+
if (!fresh && hit && now() - hit.at < ttlMs) return hit.value;
|
|
89
|
+
let binPath = null;
|
|
90
|
+
for (const dir of dirs) {
|
|
91
|
+
const candidate = join(dir, name);
|
|
92
|
+
try {
|
|
93
|
+
// 仅 `access(X_OK)` 不够:同名**目录**也过。必须确认是常规文件(符号链接跟随)。
|
|
94
|
+
if (!statSync(candidate).isFile()) continue;
|
|
95
|
+
accessSync(candidate, FS.X_OK);
|
|
96
|
+
binPath = candidate;
|
|
97
|
+
break;
|
|
98
|
+
} catch { /* 换下一个目录 */ }
|
|
99
|
+
}
|
|
100
|
+
const value = { installed: Boolean(binPath), binPath, searched: dirs };
|
|
101
|
+
detectCache.set(key, { at: now(), value });
|
|
102
|
+
return value;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 清探测缓存(测试与「刚装完想立刻看到」用)。 */
|
|
106
|
+
export function resetExecutorDetectCache() { detectCache.clear(); }
|
|
107
|
+
|
|
108
|
+
/** 读版本号(拿不到就是 `null`,**不抛**:版本只用于 tooltip,不应让接口失败)。 */
|
|
109
|
+
export function readBinaryVersion(binPath, { timeoutMs = VERSION_TIMEOUT_MS, execFileImpl = execFile } = {}) {
|
|
110
|
+
return new Promise((resolve) => {
|
|
111
|
+
if (!binPath) { resolve(null); return; }
|
|
112
|
+
try {
|
|
113
|
+
execFileImpl(binPath, ["--version"], { timeout: timeoutMs, encoding: "utf8", maxBuffer: 256 * 1024 }, (error, stdout, stderr) => {
|
|
114
|
+
if (error) { resolve(null); return; }
|
|
115
|
+
const line = String(stdout ?? "").trim().split("\n")[0] || String(stderr ?? "").trim().split("\n")[0] || "";
|
|
116
|
+
resolve(line ? line.slice(0, 80) : null);
|
|
117
|
+
});
|
|
118
|
+
} catch { resolve(null); }
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 注册表本体。**顺序即界面顺序**(团队 → dsh → claude → codex → hermes)。
|
|
124
|
+
* `buildArgs` 只在 `kind === "cli"` 上有意义;`promptVia` 说明这条 CLI 的指令怎么给(`stdin` / `argv`)。
|
|
125
|
+
*/
|
|
126
|
+
export const EXECUTOR_SPECS = Object.freeze([
|
|
127
|
+
Object.freeze({
|
|
128
|
+
id: "team",
|
|
129
|
+
agent: "team",
|
|
130
|
+
kind: EXECUTOR_KINDS.TEAM,
|
|
131
|
+
label: "团队",
|
|
132
|
+
hint: "派发给项目执行团队(角色与成员由项目 executionTeam / teamTemplate 决定)",
|
|
133
|
+
command: null,
|
|
134
|
+
promptVia: null,
|
|
135
|
+
}),
|
|
136
|
+
Object.freeze({
|
|
137
|
+
id: "host:dsh",
|
|
138
|
+
agent: "dsh",
|
|
139
|
+
kind: EXECUTOR_KINDS.HOST_SESSION,
|
|
140
|
+
label: "DSH 宿主会话",
|
|
141
|
+
hint: "投给项目主会话执行(dsh 没有 oneshot 入口,故走宿主会话通道,不伪造 CLI)",
|
|
142
|
+
command: "dsh",
|
|
143
|
+
promptVia: null,
|
|
144
|
+
}),
|
|
145
|
+
Object.freeze({
|
|
146
|
+
id: "cli:claude",
|
|
147
|
+
agent: "claude",
|
|
148
|
+
kind: EXECUTOR_KINDS.CLI,
|
|
149
|
+
label: "Claude Code",
|
|
150
|
+
hint: "claude -p(非交互;参数可被 teamTemplate.engineer.args 整体覆盖)",
|
|
151
|
+
command: "claude",
|
|
152
|
+
promptVia: "stdin",
|
|
153
|
+
buildArgs: ({ cwd, settings }) => cliArgsFor({ executorId: "cli:claude", cwd, settings }),
|
|
154
|
+
}),
|
|
155
|
+
Object.freeze({
|
|
156
|
+
id: "cli:codex",
|
|
157
|
+
agent: "codex",
|
|
158
|
+
kind: EXECUTOR_KINDS.CLI,
|
|
159
|
+
label: "Codex",
|
|
160
|
+
hint: "codex exec(workspace-write 沙箱;prompt 走 stdin)",
|
|
161
|
+
command: "codex",
|
|
162
|
+
promptVia: "stdin",
|
|
163
|
+
buildArgs: ({ cwd }) => ["exec", "-s", "workspace-write", "-C", cwd, "-"],
|
|
164
|
+
}),
|
|
165
|
+
Object.freeze({
|
|
166
|
+
id: "cli:hermes",
|
|
167
|
+
agent: "hermes",
|
|
168
|
+
kind: EXECUTOR_KINDS.CLI,
|
|
169
|
+
label: "Hermes",
|
|
170
|
+
hint: "hermes -z(一次一答、跳审批;prompt 走 argv)",
|
|
171
|
+
command: "hermes",
|
|
172
|
+
promptVia: "argv",
|
|
173
|
+
buildArgs: ({ cwd, prompt }) => ["-z", String(prompt ?? ""), "--in", cwd, "--yolo"],
|
|
174
|
+
}),
|
|
175
|
+
]);
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* 执行者 id 归一:既接受全标识(`cli:codex` / `host:dsh`),也接受裸的 agent 名(`codex` / `dsh` / `team`)。
|
|
179
|
+
* 裸名只在**唯一命中**时归一;命中不了原样返回(交给上层判「未知执行者」)。
|
|
180
|
+
*/
|
|
181
|
+
export function normalizeExecutorId(raw) {
|
|
182
|
+
const text = String(raw ?? "").trim();
|
|
183
|
+
if (!text) return null;
|
|
184
|
+
if (text.includes(":")) return text;
|
|
185
|
+
const hits = EXECUTOR_SPECS.filter((spec) => spec.agent === text || spec.id === text);
|
|
186
|
+
return hits.length === 1 ? hits[0].id : text;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 按 id / 裸名找注册项(找不到回 `null`,**不抛** —— 抛什么错误归路由层定)。 */
|
|
190
|
+
export function findExecutorSpec(raw) {
|
|
191
|
+
const id = normalizeExecutorId(raw);
|
|
192
|
+
if (!id) return null;
|
|
193
|
+
return EXECUTOR_SPECS.find((spec) => spec.id === id) ?? null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** 项目的禁用清单(`teamTemplate.forbiddenExecutors`)——全标识与裸 agent 名都算命中。 */
|
|
197
|
+
export function forbiddenSetOf(settings) {
|
|
198
|
+
return new Set((settings?.teamTemplate?.forbiddenExecutors ?? []).map((x) => String(x)));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function isExecutorForbidden(spec, settings) {
|
|
202
|
+
if (!spec) return false;
|
|
203
|
+
const forbidden = forbiddenSetOf(settings);
|
|
204
|
+
return forbidden.has(spec.id) || forbidden.has(spec.agent);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* CLI 参数(传 `prompt` 是因为 hermes 走 argv)。
|
|
209
|
+
* 非 CLI 形态回 `null`(团队 / 宿主会话不 spawn 子进程)。
|
|
210
|
+
*/
|
|
211
|
+
export function buildExecutorArgs(spec, { cwd = null, settings = null, prompt = "" } = {}) {
|
|
212
|
+
if (!spec || spec.kind !== EXECUTOR_KINDS.CLI || typeof spec.buildArgs !== "function") return null;
|
|
213
|
+
const args = spec.buildArgs({ cwd, settings, prompt });
|
|
214
|
+
return Array.isArray(args) ? args.map(String) : null;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* 列出全部执行者及**当下能不能用**。
|
|
219
|
+
*
|
|
220
|
+
* 三处「不可用」要分开说清,别混成一句「不可用」:
|
|
221
|
+
* · 未安装(CLI 找不到可执行文件)—— 人能自己装
|
|
222
|
+
* · 被项目禁用(`forbiddenExecutors`)—— 要改项目设置,**优先级最高**
|
|
223
|
+
* · 通道不成立(宿主实例没有会话通道 / 项目没配执行团队)—— 换环境或先配团队
|
|
224
|
+
*
|
|
225
|
+
* `hostSessionAvailable` / `teamAvailable` 传 `null` 表示「**判不准**」——按可用处理,
|
|
226
|
+
* 不把「不知道」冒充成「不可用」(本仓既有纪律:判不准时不得谎报失效)。
|
|
227
|
+
*/
|
|
228
|
+
export async function listExecutors({
|
|
229
|
+
settings = null, hostSessionAvailable = null, teamAvailable = null,
|
|
230
|
+
env = process.env, withVersion = true, now = () => Date.now(), fresh = false,
|
|
231
|
+
detect = null, readVersion = readBinaryVersion, versionTimeoutMs = VERSION_TIMEOUT_MS,
|
|
232
|
+
} = {}) {
|
|
233
|
+
const forbidden = forbiddenSetOf(settings);
|
|
234
|
+
const probeOf = detect ?? ((command, opts) => detectBinary(command, opts));
|
|
235
|
+
// 第一遍:形态与安装态(同步、无子进程)。
|
|
236
|
+
const rows = EXECUTOR_SPECS.map((spec) => {
|
|
237
|
+
let installed = true;
|
|
238
|
+
let binPath = null;
|
|
239
|
+
let reason = null;
|
|
240
|
+
if (spec.kind === EXECUTOR_KINDS.CLI) {
|
|
241
|
+
const probe = probeOf(spec.command, { env, now, fresh });
|
|
242
|
+
installed = Boolean(probe?.installed);
|
|
243
|
+
binPath = probe?.binPath ?? null;
|
|
244
|
+
if (!installed) reason = `未检测到 ${spec.command}(已查 PATH · ~/.npm-global/bin · ~/.local/bin · /opt/homebrew/bin)`;
|
|
245
|
+
} else if (spec.kind === EXECUTOR_KINDS.HOST_SESSION) {
|
|
246
|
+
// `null` = 判不准 ⇒ 按可用处理(不把「不知道」冒充成「不可用」)。
|
|
247
|
+
installed = hostSessionAvailable !== false;
|
|
248
|
+
if (installed === false) reason = "宿主会话通道不可用(该实例没有 sessionController / prompt:独立进程实例做不到)";
|
|
249
|
+
} else if (spec.kind === EXECUTOR_KINDS.TEAM) {
|
|
250
|
+
installed = teamAvailable !== false;
|
|
251
|
+
if (installed === false) reason = "项目未配置执行团队(teamTemplate.executionTeam 为空):先建团队或去配置页选择";
|
|
252
|
+
}
|
|
253
|
+
const blocked = forbidden.has(spec.id) || forbidden.has(spec.agent);
|
|
254
|
+
if (blocked) reason = `项目 forbiddenExecutors 已禁 ${spec.id}:项目禁用的执行者不得按卡选择`;
|
|
255
|
+
return { spec, installed, binPath, version: null, blocked, reason };
|
|
256
|
+
});
|
|
257
|
+
// 第二遍:版本号**并行**探测(拿不到就 null;不参与 usable 判定)。
|
|
258
|
+
if (withVersion) {
|
|
259
|
+
const targets = rows.filter((row) => row.spec.kind === EXECUTOR_KINDS.CLI && row.binPath);
|
|
260
|
+
const versions = await Promise.all(targets.map((row) => Promise.resolve()
|
|
261
|
+
.then(() => readVersion(row.binPath, { timeoutMs: versionTimeoutMs }))
|
|
262
|
+
.catch(() => null)));
|
|
263
|
+
targets.forEach((row, index) => { row.version = versions[index] ?? null; });
|
|
264
|
+
}
|
|
265
|
+
return rows.map(({ spec, installed, binPath, version, blocked, reason }) => ({
|
|
266
|
+
id: spec.id,
|
|
267
|
+
agent: spec.agent,
|
|
268
|
+
kind: spec.kind,
|
|
269
|
+
label: spec.label,
|
|
270
|
+
hint: spec.hint,
|
|
271
|
+
command: spec.command,
|
|
272
|
+
installed,
|
|
273
|
+
binPath,
|
|
274
|
+
version,
|
|
275
|
+
blocked,
|
|
276
|
+
usable: installed && !blocked,
|
|
277
|
+
reason,
|
|
278
|
+
}));
|
|
279
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* instance-lease.mjs —— 多实例「单写者」租约(卡 `-237` / 需求 `R173`)。
|
|
3
|
+
*
|
|
4
|
+
* 背景(真机 2026-11-10):dsh web 与 dsh desktop 可以**同时**打开同一个库。两个宿主各自
|
|
5
|
+
* 起一份插件实例,而 `index.js` 里有两处**按进程**的行为:
|
|
6
|
+
* ① 启动期 `reconcileOrphanRuns({ boot: true })` —— 它分不清「上一进程」与「另一个活着的进程」,
|
|
7
|
+
* 会把对端正**在跑**的执行当孤儿结清;
|
|
8
|
+
* ② 30s 执行循环 —— 两边各起一个定时器,同一张卡可能被**双派发**。
|
|
9
|
+
* ⇒ 同一时刻只允许一个实例是 `writer`;其余降级为 `follower`(只读、不起循环、不做 boot 收口)。
|
|
10
|
+
*
|
|
11
|
+
* 语义(刻意保守):
|
|
12
|
+
* - 表只有一行(`id = 1`),心跳 15s、过期 45s;
|
|
13
|
+
* - **不夺权**:对端心跳还新鲜就老实当 follower —— 静默夺权比只读更危险;
|
|
14
|
+
* - 只有对端**已过期**才接管,并回 `tookOver: true`(调用方据此补一次 boot 收口);
|
|
15
|
+
* - 释放是尽力而为:进程被 kill 时行会留到过期,接管方自然会接上。
|
|
16
|
+
* - **默认 role = writer**:不开租约的调用方(CLI / 测试 / 单进程)行为一字不变。
|
|
17
|
+
*/
|
|
18
|
+
export const LEASE_TTL_MS = 45_000;
|
|
19
|
+
export const LEASE_HEARTBEAT_MS = 15_000;
|
|
20
|
+
|
|
21
|
+
const CREATE_LEASE_TABLE = `create table if not exists db_instance_lease (
|
|
22
|
+
id integer primary key check (id = 1),
|
|
23
|
+
instance_id text not null,
|
|
24
|
+
host text not null,
|
|
25
|
+
pid integer not null,
|
|
26
|
+
started_at text not null,
|
|
27
|
+
heartbeat_at integer not null
|
|
28
|
+
)`;
|
|
29
|
+
|
|
30
|
+
export function createLeaseApi({ db, nowIso, randomUUID }) {
|
|
31
|
+
db.exec(CREATE_LEASE_TABLE);
|
|
32
|
+
let role = "writer";
|
|
33
|
+
let owner = null;
|
|
34
|
+
let selfId = null;
|
|
35
|
+
|
|
36
|
+
const readRow = () => db.prepare("select * from db_instance_lease where id = 1").get() ?? null;
|
|
37
|
+
const describe = (row) => (row
|
|
38
|
+
? { instanceId: row.instance_id, host: row.host, pid: row.pid, startedAt: row.started_at, heartbeatAt: row.heartbeat_at }
|
|
39
|
+
: null);
|
|
40
|
+
|
|
41
|
+
return {
|
|
42
|
+
/**
|
|
43
|
+
* 抢/续租约。**幂等**:同一个 instanceId 重复调用等于心跳。
|
|
44
|
+
* @returns {{role:"writer"|"follower", owner:object|null, tookOver:boolean, previous?:object|null, instanceId:string}}
|
|
45
|
+
*/
|
|
46
|
+
acquireInstanceLease({ host = "local", pid = process.pid, nowMs = Date.now(), ttlMs = LEASE_TTL_MS, instanceId } = {}) {
|
|
47
|
+
const self = instanceId || selfId || (selfId = `inst-${randomUUID().replace(/-/g, "").slice(0, 10)}`);
|
|
48
|
+
const stamp = nowIso();
|
|
49
|
+
const row = readRow();
|
|
50
|
+
if (!row) {
|
|
51
|
+
db.prepare("insert into db_instance_lease (id, instance_id, host, pid, started_at, heartbeat_at) values (1, ?, ?, ?, ?, ?)")
|
|
52
|
+
.run(self, String(host), Number(pid), stamp, Number(nowMs));
|
|
53
|
+
role = "writer"; owner = null;
|
|
54
|
+
return { role, owner: null, tookOver: false, instanceId: self };
|
|
55
|
+
}
|
|
56
|
+
if (row.instance_id === self) {
|
|
57
|
+
db.prepare("update db_instance_lease set heartbeat_at = ?, host = ?, pid = ? where id = 1")
|
|
58
|
+
.run(Number(nowMs), String(host), Number(pid));
|
|
59
|
+
role = "writer"; owner = null;
|
|
60
|
+
return { role, owner: null, tookOver: false, instanceId: self };
|
|
61
|
+
}
|
|
62
|
+
const age = Number(nowMs) - Number(row.heartbeat_at ?? 0);
|
|
63
|
+
if (age <= Number(ttlMs)) {
|
|
64
|
+
role = "follower"; owner = describe(row);
|
|
65
|
+
return { role, owner, tookOver: false, instanceId: self };
|
|
66
|
+
}
|
|
67
|
+
const previous = describe(row);
|
|
68
|
+
db.prepare("update db_instance_lease set instance_id = ?, host = ?, pid = ?, started_at = ?, heartbeat_at = ? where id = 1")
|
|
69
|
+
.run(self, String(host), Number(pid), stamp, Number(nowMs));
|
|
70
|
+
role = "writer"; owner = null;
|
|
71
|
+
return { role, owner: null, tookOver: true, previous, instanceId: self };
|
|
72
|
+
},
|
|
73
|
+
|
|
74
|
+
/** 本实例当前角色(**本地缓存**,只在 acquire 时更新)。未调用过 acquire 的调用方恒为 `writer`(零行为变化)。 */
|
|
75
|
+
instanceRole() { return role; },
|
|
76
|
+
|
|
77
|
+
/** follower 时是「谁在写」;writer 时为 null。 */
|
|
78
|
+
instanceLeaseOwner() { return owner; },
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* **现读**当前角色(每个写请求都要用这一条,不要用上面的缓存):
|
|
82
|
+
* 缓存最多滞后一个心跳周期(15s)——被夺权的一方在这 15s 里仍会以为自己是 writer,
|
|
83
|
+
* 若写门只看缓存,就有一段真实的双写窗口。这里直接读那一行,代价是一次主键查询。
|
|
84
|
+
* 行不存在 / 是自己 / 对端已过期 ⇒ `writer`(过期由下一次心跳正式接管)。
|
|
85
|
+
*/
|
|
86
|
+
instanceRoleFresh() {
|
|
87
|
+
const row = readRow();
|
|
88
|
+
if (!row) return "writer";
|
|
89
|
+
if (selfId && row.instance_id === selfId) return "writer";
|
|
90
|
+
const age = Date.now() - Number(row.heartbeat_at ?? 0);
|
|
91
|
+
return age <= LEASE_TTL_MS ? "follower" : "writer";
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
/** 现读「谁在写」(搭配 instanceRoleFresh,仅 follower 时非 null)。 */
|
|
95
|
+
instanceLeaseOwnerFresh() {
|
|
96
|
+
const row = readRow();
|
|
97
|
+
if (!row || (selfId && row.instance_id === selfId)) return null;
|
|
98
|
+
const age = Date.now() - Number(row.heartbeat_at ?? 0);
|
|
99
|
+
return age <= LEASE_TTL_MS ? describe(row) : null;
|
|
100
|
+
},
|
|
101
|
+
|
|
102
|
+
/** 释放租约(仅当本实例是持有者)。返回是否真的释放了。 */
|
|
103
|
+
releaseInstanceLease() {
|
|
104
|
+
const row = readRow();
|
|
105
|
+
if (row && selfId && row.instance_id === selfId) {
|
|
106
|
+
db.prepare("delete from db_instance_lease where id = 1").run();
|
|
107
|
+
role = "writer"; owner = null;
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
return false;
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|