@yourstandby/fabric 0.0.0-stage → 0.1.0
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/README.md +24 -2
- package/dist/daemon.js +3797 -0
- package/dist/index.js +3916 -0
- package/package.json +30 -4
- package/src/artifacts.test.ts +148 -0
- package/src/artifacts.ts +247 -0
- package/src/daemon-runner.ts +218 -0
- package/src/daemon.ts +524 -0
- package/src/discovery.ts +332 -0
- package/src/dispatch.test.ts +154 -0
- package/src/dispatch.ts +459 -0
- package/src/dispatcher.test.ts +321 -0
- package/src/dispatcher.ts +794 -0
- package/src/fabric-apply.test.ts +115 -0
- package/src/fabric-apply.ts +137 -0
- package/src/fabric-avatar.test.ts +51 -0
- package/src/fabric-discovery.test.ts +100 -0
- package/src/fabric-history.test.ts +68 -0
- package/src/fabric-keepalive.test.ts +112 -0
- package/src/fabric-notify.test.ts +269 -0
- package/src/fabric-pairing.test.ts +164 -0
- package/src/fabric-runner.test.ts +113 -0
- package/src/fabric-runner.ts +167 -0
- package/src/fabric-score.test.ts +74 -0
- package/src/fabric-server.ts +101 -0
- package/src/fabric-service.test.ts +279 -0
- package/src/fabric-service.ts +745 -0
- package/src/fabric-view.test.ts +118 -0
- package/src/fabric-view.ts +182 -0
- package/src/fabric-worktree.test.ts +139 -0
- package/src/fabric-worktree.ts +232 -0
- package/src/history.ts +127 -0
- package/src/host-load.ts +18 -0
- package/src/index.ts +27 -0
- package/src/pairing.test.ts +212 -0
- package/src/pairing.ts +342 -0
- package/src/peer-store.test.ts +212 -0
- package/src/peer-store.ts +243 -0
- package/src/transport.test.ts +247 -0
- package/src/transport.ts +709 -0
package/src/discovery.ts
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 一键检索匹配:UDP 广播发现同局域网的已配对机器(跨网走 MagicDNS 主机名,不用这里)。
|
|
3
|
+
*
|
|
4
|
+
* 端口按节点名散列:base + fnv1a(node) % span,双方各自绑自己的探测口,
|
|
5
|
+
* 探测包里带 ctx 和想要的节点名,答对的才回。
|
|
6
|
+
*/
|
|
7
|
+
import { createSocket, type Socket as UdpSocket } from "node:dgram";
|
|
8
|
+
import { networkInterfaces } from "node:os";
|
|
9
|
+
import {
|
|
10
|
+
FABRIC_CTX_MAX_CHARS,
|
|
11
|
+
FABRIC_PROTOCOL_VERSION,
|
|
12
|
+
checkProtocolVersion,
|
|
13
|
+
} from "../../../contract/domains/fabric.ts";
|
|
14
|
+
|
|
15
|
+
export const DISC_PORT_BASE = 7_800;
|
|
16
|
+
export const DISC_SPAN = 100;
|
|
17
|
+
export const DISC_TIMEOUT_MS = 1_200;
|
|
18
|
+
const MAX_PACKET_BYTES = 512;
|
|
19
|
+
|
|
20
|
+
export function fnv1a(text: string): number {
|
|
21
|
+
let hash = 0x811c9dc5;
|
|
22
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
23
|
+
hash ^= text.charCodeAt(index);
|
|
24
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
25
|
+
}
|
|
26
|
+
return hash >>> 0;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function discoveryPort(nodeName: string, base = DISC_PORT_BASE, span = DISC_SPAN): number {
|
|
30
|
+
return base + (fnv1a(nodeName) % Math.max(1, span));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function sanitizeCtx(ctx: string): string {
|
|
34
|
+
return ctx.trim().slice(0, FABRIC_CTX_MAX_CHARS);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ResponderOptions {
|
|
38
|
+
nodeName: string;
|
|
39
|
+
tcpPort: number;
|
|
40
|
+
ctx: string;
|
|
41
|
+
base?: number;
|
|
42
|
+
span?: number;
|
|
43
|
+
log?: (message: string) => void;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface DiscoveryResponder {
|
|
47
|
+
port: number;
|
|
48
|
+
close(): Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 应答线程:收到 SBF1|<ctx>|<wantNode> 且 want == 本节点名时回 SBF2|<node>|<port>。 */
|
|
52
|
+
export async function startResponder(options: ResponderOptions): Promise<DiscoveryResponder> {
|
|
53
|
+
const port = discoveryPort(options.nodeName, options.base, options.span);
|
|
54
|
+
const ctx = sanitizeCtx(options.ctx);
|
|
55
|
+
const socket: UdpSocket = createSocket({ type: "udp4", reuseAddr: true });
|
|
56
|
+
await new Promise<void>((resolve, reject) => {
|
|
57
|
+
socket.once("error", reject);
|
|
58
|
+
socket.bind(port, "0.0.0.0", () => {
|
|
59
|
+
socket.removeListener("error", reject);
|
|
60
|
+
resolve();
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
socket.on("message", (packet, from) => {
|
|
64
|
+
if (packet.length > MAX_PACKET_BYTES) return;
|
|
65
|
+
const text = packet.toString("utf8");
|
|
66
|
+
const parts = text.split("|");
|
|
67
|
+
if (parts.length !== 4 || parts[0] !== "SBF1") return;
|
|
68
|
+
if (parts[1] !== ctx) return;
|
|
69
|
+
if (parts[2] !== options.nodeName) return;
|
|
70
|
+
const protocol = checkProtocolVersion(parts[3]);
|
|
71
|
+
if (!protocol.ok) {
|
|
72
|
+
// 版本不合也要留下痕迹:否则「扫不到」只能靠猜。
|
|
73
|
+
options.log?.(`disc probe from ${from.address} rejected: ${protocol.reason}`);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const reply = `SBF2|${options.nodeName}|${options.tcpPort}|${FABRIC_PROTOCOL_VERSION}`;
|
|
77
|
+
socket.send(Buffer.from(reply, "utf8"), from.port, from.address, () => {
|
|
78
|
+
options.log?.(`disc answered ${from.address} -> ${reply}`);
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
socket.on("error", (error) => options.log?.(`disc socket error: ${error.message}`));
|
|
82
|
+
return {
|
|
83
|
+
port,
|
|
84
|
+
close: () =>
|
|
85
|
+
new Promise<void>((resolve) => {
|
|
86
|
+
try {
|
|
87
|
+
socket.close(() => resolve());
|
|
88
|
+
} catch {
|
|
89
|
+
resolve();
|
|
90
|
+
}
|
|
91
|
+
}),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface DiscoverOptions {
|
|
96
|
+
wantNode: string;
|
|
97
|
+
ctx: string;
|
|
98
|
+
base?: number;
|
|
99
|
+
span?: number;
|
|
100
|
+
timeoutMs?: number;
|
|
101
|
+
log?: (message: string) => void;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 广播探测想要的节点,返回 "host:port"。
|
|
106
|
+
*
|
|
107
|
+
* 同时打 127.0.0.1 和广播地址:同机双实例、局域网两种情况一条路径覆盖。
|
|
108
|
+
*/
|
|
109
|
+
export async function discoverPeer(options: DiscoverOptions): Promise<string | null> {
|
|
110
|
+
const port = discoveryPort(options.wantNode, options.base, options.span);
|
|
111
|
+
const ctx = sanitizeCtx(options.ctx);
|
|
112
|
+
const socket = createSocket({ type: "udp4" });
|
|
113
|
+
await new Promise<void>((resolve, reject) => {
|
|
114
|
+
socket.once("error", reject);
|
|
115
|
+
socket.bind(0, "0.0.0.0", () => {
|
|
116
|
+
socket.removeListener("error", reject);
|
|
117
|
+
resolve();
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
const probe = Buffer.from(`SBF1|${ctx}|${options.wantNode}|${FABRIC_PROTOCOL_VERSION}`, "utf8");
|
|
121
|
+
return new Promise<string | null>((resolve) => {
|
|
122
|
+
let settled = false;
|
|
123
|
+
const finish = (value: string | null) => {
|
|
124
|
+
if (settled) return;
|
|
125
|
+
settled = true;
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
try {
|
|
128
|
+
socket.close();
|
|
129
|
+
} catch {
|
|
130
|
+
// 已关闭
|
|
131
|
+
}
|
|
132
|
+
resolve(value);
|
|
133
|
+
};
|
|
134
|
+
const timer = setTimeout(() => finish(null), options.timeoutMs ?? DISC_TIMEOUT_MS);
|
|
135
|
+
timer.unref?.();
|
|
136
|
+
socket.on("message", (packet, from) => {
|
|
137
|
+
if (packet.length > MAX_PACKET_BYTES) return;
|
|
138
|
+
const parts = packet.toString("utf8").split("|");
|
|
139
|
+
if (parts.length !== 4 || parts[0] !== "SBF2") return;
|
|
140
|
+
if (parts[1] !== options.wantNode) return;
|
|
141
|
+
const protocol = checkProtocolVersion(parts[3]);
|
|
142
|
+
if (!protocol.ok) {
|
|
143
|
+
options.log?.(`disc reply from ${from.address} rejected: ${protocol.reason}`);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const tcpPort = Number.parseInt(parts[2], 10);
|
|
147
|
+
if (!Number.isInteger(tcpPort) || tcpPort < 1 || tcpPort > 65535) return;
|
|
148
|
+
options.log?.(`disc discovered ${parts[1]} at ${from.address}:${tcpPort}`);
|
|
149
|
+
finish(`${from.address}:${tcpPort}`);
|
|
150
|
+
});
|
|
151
|
+
socket.send(probe, port, "127.0.0.1", () => {});
|
|
152
|
+
socket.send(probe, port, "255.255.255.255", () => {});
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/* ------------------------------------------------------------------ *
|
|
157
|
+
* 匿名广播(SBF3 / SBF4):让对方在「零输入」的情况下看得见本机。
|
|
158
|
+
*
|
|
159
|
+
* 与上面的 SBF1/SBF2 是两条独立通道,互不影响:
|
|
160
|
+
* SBF1/SBF2 = 按节点名点名(跨网、已知目标、已配对场景)
|
|
161
|
+
* SBF3/SBF4 = 谁在问都答(同局域网发现,不需要预先知道对方是谁)
|
|
162
|
+
*
|
|
163
|
+
* 回包只带 nodeId / 端口 / 版本:头像由 nodeId 在本地派生,不额外暴露信息。
|
|
164
|
+
* ------------------------------------------------------------------ */
|
|
165
|
+
|
|
166
|
+
export const DISC_ANNOUNCE_PORT = 7_799;
|
|
167
|
+
const ANNOUNCE_PROBE = "SBF3";
|
|
168
|
+
const ANNOUNCE_REPLY = "SBF4";
|
|
169
|
+
/** 一轮扫两次:WiFi 上 UDP 丢包是常态,只发一次会漏机器。 */
|
|
170
|
+
export const SCAN_RESEND_MS = 400;
|
|
171
|
+
|
|
172
|
+
export interface NearbyDevice {
|
|
173
|
+
nodeId: string;
|
|
174
|
+
shortId: string;
|
|
175
|
+
tcpPort: number;
|
|
176
|
+
appVersion: string;
|
|
177
|
+
address: string;
|
|
178
|
+
/** 对端声明的线上协议版本;不一致时 scanLan 不会把它当成可配对目标。 */
|
|
179
|
+
protocolVersion: number;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export interface AnnouncerOptions {
|
|
183
|
+
nodeId: string;
|
|
184
|
+
tcpPort: number;
|
|
185
|
+
appVersion?: string;
|
|
186
|
+
/** 关掉后不再应答扫描;已配对的点名探测(SBF1)不受影响。 */
|
|
187
|
+
enabled?: () => boolean;
|
|
188
|
+
port?: number;
|
|
189
|
+
log?: (message: string) => void;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export interface Announcer {
|
|
193
|
+
port: number;
|
|
194
|
+
close(): Promise<void>;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function sanitizeVersion(raw: string | undefined): string {
|
|
198
|
+
return (raw ?? "").replace(/[|\s]/g, "").slice(0, 24);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function closeQuietly(socket: UdpSocket): Promise<void> {
|
|
202
|
+
return new Promise<void>((resolve) => {
|
|
203
|
+
try {
|
|
204
|
+
socket.close(() => resolve());
|
|
205
|
+
} catch {
|
|
206
|
+
resolve();
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** 应答线程:收到 SBF3 就回 SBF4(除非用户关掉了「允许局域网发现」)。 */
|
|
212
|
+
export async function startAnnouncer(options: AnnouncerOptions): Promise<Announcer> {
|
|
213
|
+
let port = options.port ?? DISC_ANNOUNCE_PORT;
|
|
214
|
+
const version = sanitizeVersion(options.appVersion);
|
|
215
|
+
const socket: UdpSocket = createSocket({ type: "udp4", reuseAddr: true });
|
|
216
|
+
await new Promise<void>((resolve, reject) => {
|
|
217
|
+
socket.once("error", reject);
|
|
218
|
+
socket.bind(port, "0.0.0.0", () => {
|
|
219
|
+
socket.removeListener("error", reject);
|
|
220
|
+
resolve();
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
// port 传 0 时内核会分配临时端口:回给调用方的必须是真实端口,否则没人扫得到。
|
|
224
|
+
const bound = socket.address();
|
|
225
|
+
if (bound && typeof bound === "object") port = bound.port;
|
|
226
|
+
socket.on("message", (packet, from) => {
|
|
227
|
+
if (packet.length > MAX_PACKET_BYTES) return;
|
|
228
|
+
const parts = packet.toString("utf8").split("|");
|
|
229
|
+
if (parts.length !== 3 || parts[0] !== ANNOUNCE_PROBE) return;
|
|
230
|
+
if (options.enabled && !options.enabled()) return;
|
|
231
|
+
const protocol = checkProtocolVersion(parts[2]);
|
|
232
|
+
if (!protocol.ok) {
|
|
233
|
+
options.log?.(`fabric announce ignored ${from.address}: ${protocol.reason}`);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const reply = `${ANNOUNCE_REPLY}|${options.nodeId}|${options.tcpPort}|${FABRIC_PROTOCOL_VERSION}|${version}`;
|
|
237
|
+
socket.send(Buffer.from(reply, "utf8"), from.port, from.address, (error) => {
|
|
238
|
+
if (error) options.log?.(`fabric announce reply failed: ${error.message}`);
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
socket.on("error", (error) => options.log?.(`fabric announce socket error: ${error.message}`));
|
|
242
|
+
return {
|
|
243
|
+
port,
|
|
244
|
+
close: () => closeQuietly(socket),
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* 广播地址列表:必须按网卡算,只打 255.255.255.255 在多网卡/VPN 机器上会漏。
|
|
250
|
+
* 以 127.0.0.1 兜底,同机双实例也能互相发现。
|
|
251
|
+
*/
|
|
252
|
+
export function broadcastAddresses(): string[] {
|
|
253
|
+
const targets = new Set<string>(["255.255.255.255", "127.0.0.1"]);
|
|
254
|
+
for (const list of Object.values(networkInterfaces())) {
|
|
255
|
+
for (const info of list ?? []) {
|
|
256
|
+
if (info.family !== "IPv4" || info.internal) continue;
|
|
257
|
+
targets.add(broadcastOf(info.address, info.netmask));
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return [...targets];
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function broadcastOf(address: string, netmask: string | undefined): string {
|
|
264
|
+
const ip = address.split(".").map((part) => Number.parseInt(part, 10));
|
|
265
|
+
const mask = (netmask ?? "255.255.255.255").split(".").map((part) => Number.parseInt(part, 10));
|
|
266
|
+
if (ip.length !== 4 || mask.length !== 4 || mask.some((part) => !Number.isInteger(part))) {
|
|
267
|
+
return "255.255.255.255";
|
|
268
|
+
}
|
|
269
|
+
return ip.map((part, index) => (part | (~(mask[index] ?? 255) & 255)) & 255).join(".");
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export interface ScanLanOptions {
|
|
273
|
+
timeoutMs?: number;
|
|
274
|
+
port?: number;
|
|
275
|
+
log?: (message: string) => void;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** 扫一圈:只返回回话的设备,重复 nodeId 去重(同一台机器可能从两块网卡回来)。 */
|
|
279
|
+
export async function scanLan(options: ScanLanOptions = {}): Promise<NearbyDevice[]> {
|
|
280
|
+
const port = options.port ?? DISC_ANNOUNCE_PORT;
|
|
281
|
+
const socket: UdpSocket = createSocket({ type: "udp4", reuseAddr: true });
|
|
282
|
+
try {
|
|
283
|
+
socket.setBroadcast(true);
|
|
284
|
+
} catch {
|
|
285
|
+
// 某些平台/沙箱不支持:退化成单播到 127.0.0.1,至少同机能发现。
|
|
286
|
+
}
|
|
287
|
+
const found = new Map<string, NearbyDevice>();
|
|
288
|
+
await new Promise<void>((resolve, reject) => {
|
|
289
|
+
socket.once("error", reject);
|
|
290
|
+
socket.bind(0, () => {
|
|
291
|
+
socket.removeListener("error", reject);
|
|
292
|
+
resolve();
|
|
293
|
+
});
|
|
294
|
+
});
|
|
295
|
+
socket.on("message", (packet, from) => {
|
|
296
|
+
if (packet.length > MAX_PACKET_BYTES) return;
|
|
297
|
+
const parts = packet.toString("utf8").split("|");
|
|
298
|
+
if (parts.length < 4 || parts[0] !== ANNOUNCE_REPLY) return;
|
|
299
|
+
const nodeId = parts[1] ?? "";
|
|
300
|
+
if (!/^[0-9a-f]{8,64}$/i.test(nodeId)) return;
|
|
301
|
+
const tcpPort = Number.parseInt(parts[2] ?? "", 10);
|
|
302
|
+
if (!Number.isInteger(tcpPort) || tcpPort < 1 || tcpPort > 65535) return;
|
|
303
|
+
const protocol = checkProtocolVersion(parts[3]);
|
|
304
|
+
if (!protocol.ok) {
|
|
305
|
+
options.log?.(`fabric scan ignored ${from.address}: ${protocol.reason}`);
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
found.set(nodeId, {
|
|
309
|
+
nodeId,
|
|
310
|
+
shortId: nodeId.slice(0, 4),
|
|
311
|
+
tcpPort,
|
|
312
|
+
appVersion: parts[4] ?? "",
|
|
313
|
+
protocolVersion: protocol.version,
|
|
314
|
+
address: from.address,
|
|
315
|
+
});
|
|
316
|
+
});
|
|
317
|
+
socket.on("error", (error) => options.log?.(`fabric scan socket error: ${error.message}`));
|
|
318
|
+
const targets = broadcastAddresses();
|
|
319
|
+
const probe = Buffer.from(`${ANNOUNCE_PROBE}|${Date.now().toString(36)}|${FABRIC_PROTOCOL_VERSION}`, "utf8");
|
|
320
|
+
const sendAll = () => {
|
|
321
|
+
for (const target of targets) socket.send(probe, port, target, () => {});
|
|
322
|
+
};
|
|
323
|
+
sendAll();
|
|
324
|
+
await new Promise<void>((resolve) => {
|
|
325
|
+
const resend = setTimeout(sendAll, SCAN_RESEND_MS);
|
|
326
|
+
const end = setTimeout(resolve, options.timeoutMs ?? DISC_TIMEOUT_MS);
|
|
327
|
+
resend.unref?.();
|
|
328
|
+
end.unref?.();
|
|
329
|
+
});
|
|
330
|
+
await closeQuietly(socket);
|
|
331
|
+
return [...found.values()];
|
|
332
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import {
|
|
7
|
+
PEER_MAX_QUEUE,
|
|
8
|
+
REMOTE_MIN_ESTIMATE_MS,
|
|
9
|
+
TaskLedger,
|
|
10
|
+
choosePeer,
|
|
11
|
+
isTerminalState,
|
|
12
|
+
taskIdFor,
|
|
13
|
+
} from "./dispatch.ts";
|
|
14
|
+
|
|
15
|
+
function peer(overrides: Record<string, unknown> = {}) {
|
|
16
|
+
return {
|
|
17
|
+
nodeId: "0123456789abcdef",
|
|
18
|
+
name: "机-A",
|
|
19
|
+
online: true,
|
|
20
|
+
hbAgeMs: 1_000,
|
|
21
|
+
queueDepth: PEER_MAX_QUEUE,
|
|
22
|
+
labels: ["build"],
|
|
23
|
+
grants: "workspace-rw+bash" as const,
|
|
24
|
+
...overrides,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const need = { labels: ["build"], estimatedMs: REMOTE_MIN_ESTIMATE_MS };
|
|
29
|
+
|
|
30
|
+
test("短活留在本地:跨机往返比本地跑还贵", () => {
|
|
31
|
+
const decision = choosePeer([peer()], { labels: [], estimatedMs: 3_000 });
|
|
32
|
+
assert.equal(decision.ok, false);
|
|
33
|
+
assert.equal(decision.ok === false && decision.code, "E_LOCAL_FASTER");
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test("没有已配对机器 / 全离线 / 缺标签 / 在忙 各自给出可读原因", () => {
|
|
37
|
+
const noPeers = choosePeer([], need);
|
|
38
|
+
assert.equal(noPeers.ok === false && noPeers.code, "E_NO_PEERS");
|
|
39
|
+
const offline = choosePeer([peer({ online: false })], need);
|
|
40
|
+
assert.equal(offline.ok === false && offline.code, "E_PEER_OFFLINE");
|
|
41
|
+
const stale = choosePeer([peer({ hbAgeMs: 30_000 })], need);
|
|
42
|
+
assert.equal(stale.ok === false && stale.code, "E_PEER_OFFLINE");
|
|
43
|
+
const noLabel = choosePeer([peer({ labels: ["gpu"] })], need);
|
|
44
|
+
assert.equal(noLabel.ok === false && noLabel.code, "E_NO_LABEL");
|
|
45
|
+
const busy = choosePeer([peer({ queueDepth: PEER_MAX_QUEUE + 1 })], need);
|
|
46
|
+
assert.equal(busy.ok === false && busy.code, "E_PEER_BUSY");
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("档位不够不派,权限不能拿标签抵", () => {
|
|
50
|
+
const decision = choosePeer([peer({ grants: "read-only" })], { ...need, grant: "workspace-rw" });
|
|
51
|
+
assert.equal(decision.ok === false && decision.code, "E_GRANT_TOO_LOW");
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("多个候选按队列深度、心跳、名字排序,可复现", () => {
|
|
55
|
+
const decision = choosePeer(
|
|
56
|
+
[
|
|
57
|
+
peer({ nodeId: "1111111111111111", name: "慢", hbAgeMs: 4_000 }),
|
|
58
|
+
peer({ nodeId: "2222222222222222", name: "快", hbAgeMs: 200 }),
|
|
59
|
+
peer({ nodeId: "3333333333333333", name: "更慢", hbAgeMs: 3_000 }),
|
|
60
|
+
],
|
|
61
|
+
need,
|
|
62
|
+
);
|
|
63
|
+
assert.equal(decision.ok, true);
|
|
64
|
+
assert.equal(decision.ok === true && decision.peerId, "2222222222222222");
|
|
65
|
+
assert.equal(decision.considered, 3);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
function ledgerSetup() {
|
|
69
|
+
const dir = mkdtempSync(join(tmpdir(), "pi-fabric-tasks-"));
|
|
70
|
+
return {
|
|
71
|
+
dir,
|
|
72
|
+
ledger: new TaskLedger(dir, "outbound"),
|
|
73
|
+
cleanup: () => rmSync(dir, { recursive: true, force: true }),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
test("任务 id 内容寻址:同一份任务重复派发只有一个 id", () => {
|
|
78
|
+
const a = taskIdFor({ prompt: "跑构建", deadlineClass: "build" });
|
|
79
|
+
const b = taskIdFor({ prompt: "跑构建", deadlineClass: "build" });
|
|
80
|
+
const c = taskIdFor({ prompt: "跑构建", deadlineClass: "long" });
|
|
81
|
+
assert.equal(a, b);
|
|
82
|
+
assert.notEqual(a, c);
|
|
83
|
+
assert.match(a, /^[0-9a-f]{16}$/);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test("台账落盘:create 幂等、状态推进、终态不可回退", () => {
|
|
87
|
+
const env = ledgerSetup();
|
|
88
|
+
try {
|
|
89
|
+
const taskId = taskIdFor({ prompt: "跑构建", deadlineClass: "build" });
|
|
90
|
+
const created = env.ledger.create({ taskId, peerId: "0123456789abcdef", deadlineClass: "build", now: 1_000 });
|
|
91
|
+
assert.equal(created.state, "submitted");
|
|
92
|
+
assert.equal(created.deadlineAt, 1_000 + 600_000);
|
|
93
|
+
const again = env.ledger.create({ taskId, peerId: "ffffffffffffffff", deadlineClass: "quick", now: 2_000 });
|
|
94
|
+
assert.equal(again.peerId, "0123456789abcdef");
|
|
95
|
+
assert.equal(again.deadlineClass, "build");
|
|
96
|
+
|
|
97
|
+
env.ledger.update(taskId, { state: "accepted" }, 3_000);
|
|
98
|
+
const running = env.ledger.update(taskId, { state: "running" }, 4_000);
|
|
99
|
+
assert.equal(running.startedAt, 4_000);
|
|
100
|
+
const done = env.ledger.update(taskId, { state: "done", exitCode: 0, summary: "ok" }, 5_000);
|
|
101
|
+
assert.equal(done.finishedAt, 5_000);
|
|
102
|
+
assert.equal(isTerminalState(done.state), true);
|
|
103
|
+
assert.throws(() => env.ledger.update(taskId, { state: "running" }, 6_000));
|
|
104
|
+
} finally {
|
|
105
|
+
env.cleanup();
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test("对账:超过 deadline 才判 lost,未到 deadline 不动", () => {
|
|
110
|
+
const env = ledgerSetup();
|
|
111
|
+
try {
|
|
112
|
+
const quick = taskIdFor({ prompt: "quick", deadlineClass: "quick" });
|
|
113
|
+
env.ledger.create({ taskId: quick, peerId: "0123456789abcdef", deadlineClass: "quick", now: 1_000 });
|
|
114
|
+
assert.deepEqual(env.ledger.reconcile(1_000 + 59_000).lost, []);
|
|
115
|
+
assert.deepEqual(env.ledger.reconcile(1_000 + 61_000).lost, [quick]);
|
|
116
|
+
assert.equal(env.ledger.get(quick)?.state, "lost");
|
|
117
|
+
|
|
118
|
+
const done = taskIdFor({ prompt: "done", deadlineClass: "quick" });
|
|
119
|
+
env.ledger.create({ taskId: done, peerId: "0123456789abcdef", deadlineClass: "quick", now: 1_000 });
|
|
120
|
+
env.ledger.update(done, { state: "done" }, 2_000);
|
|
121
|
+
assert.deepEqual(env.ledger.reconcile(9_999_999).lost, []);
|
|
122
|
+
} finally {
|
|
123
|
+
env.cleanup();
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test("references 汇总被引用的对象,供 artifact TTL 区分有主无主", () => {
|
|
128
|
+
const env = ledgerSetup();
|
|
129
|
+
try {
|
|
130
|
+
const taskId = taskIdFor({ prompt: "带产物", deadlineClass: "build" });
|
|
131
|
+
const input = { sha256: "a".repeat(64), len: 10, kind: "input" as const };
|
|
132
|
+
const result = { sha256: "b".repeat(64), len: 20, kind: "result" as const };
|
|
133
|
+
env.ledger.create({ taskId, peerId: "0123456789abcdef", deadlineClass: "build", inputRef: input });
|
|
134
|
+
env.ledger.update(taskId, { state: "done", resultRef: result });
|
|
135
|
+
assert.deepEqual(env.ledger.references().sort(), [input.sha256, result.sha256]);
|
|
136
|
+
} finally {
|
|
137
|
+
env.cleanup();
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test("落盘文件坏掉时当作不存在,不炸整个列表", () => {
|
|
142
|
+
const env = ledgerSetup();
|
|
143
|
+
try {
|
|
144
|
+
const good = taskIdFor({ prompt: "good", deadlineClass: "quick" });
|
|
145
|
+
env.ledger.create({ taskId: good, peerId: "0123456789abcdef", deadlineClass: "quick" });
|
|
146
|
+
writeFileSync(join(env.dir, "fabric", "tasks", "outbound", "ffffffffffffffff.json"), "{坏", "utf8");
|
|
147
|
+
assert.deepEqual(
|
|
148
|
+
env.ledger.list().map((record) => record.taskId),
|
|
149
|
+
[good],
|
|
150
|
+
);
|
|
151
|
+
} finally {
|
|
152
|
+
env.cleanup();
|
|
153
|
+
}
|
|
154
|
+
});
|