@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.
@@ -0,0 +1,115 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFileSync } from "node:child_process";
4
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { applyPatchToRepo, filesInPatch } from "./fabric-apply.ts";
8
+ import { cleanGitEnv } from "./fabric-worktree.ts";
9
+
10
+ function initRepo(): string {
11
+ const repo = mkdtempSync(join(tmpdir(), "pi-fabric-apply-repo-"));
12
+ execFileSync("git", ["init", "-q", repo], { windowsHide: true, env: cleanGitEnv() });
13
+ execFileSync("git", ["-C", repo, "config", "user.email", "t@example.com"], { windowsHide: true, env: cleanGitEnv() });
14
+ execFileSync("git", ["-C", repo, "config", "user.name", "t"], { windowsHide: true, env: cleanGitEnv() });
15
+ writeFileSync(join(repo, "a.txt"), "one\n", "utf8");
16
+ execFileSync("git", ["-C", repo, "add", "-A"], { windowsHide: true, env: cleanGitEnv() });
17
+ execFileSync("git", ["-C", repo, "commit", "-qm", "init"], { windowsHide: true, env: cleanGitEnv() });
18
+ return repo;
19
+ }
20
+
21
+ const PATCH = [
22
+ "diff --git a/a.txt b/a.txt",
23
+ "--- a/a.txt",
24
+ "+++ b/a.txt",
25
+ "@@ -1 +1,2 @@",
26
+ " one",
27
+ "+two",
28
+ "",
29
+ ].join("\n");
30
+
31
+ test("dry-run 默认:能干净应用也不写文件", async () => {
32
+ const repo = initRepo();
33
+ try {
34
+ const result = await applyPatchToRepo({ repo, patch: Buffer.from(PATCH, "utf8") });
35
+ assert.equal(result.ok, true);
36
+ assert.equal(result.ok && result.dryRun, true);
37
+ assert.equal(readFileSync(join(repo, "a.txt"), "utf8"), "one\n");
38
+ } finally {
39
+ rmSync(repo, { recursive: true, force: true });
40
+ }
41
+ });
42
+
43
+ test("确认后真的落地:文件内容变化,但不是自动提交", async () => {
44
+ const repo = initRepo();
45
+ try {
46
+ const result = await applyPatchToRepo({ repo, patch: Buffer.from(PATCH, "utf8"), dryRun: false });
47
+ assert.equal(result.ok, true);
48
+ // Windows 上 core.autocrlf 会把写入变成 CRLF,断言前先归一化
49
+ assert.equal(readFileSync(join(repo, "a.txt"), "utf8").replace(/\r\n/g, "\n"), "one\ntwo\n");
50
+ const status = execFileSync("git", ["-C", repo, "status", "--porcelain"], {
51
+ encoding: "utf8",
52
+ windowsHide: true,
53
+ env: cleanGitEnv(),
54
+ });
55
+ // 有改动但没提交:合不合、怎么提交由人决定
56
+ assert.match(status, /a\.txt/);
57
+ assert.equal(
58
+ execFileSync("git", ["-C", repo, "log", "--oneline"], {
59
+ encoding: "utf8",
60
+ windowsHide: true,
61
+ env: cleanGitEnv(),
62
+ })
63
+ .trim()
64
+ .split("\n").length,
65
+ 1,
66
+ );
67
+ } finally {
68
+ rmSync(repo, { recursive: true, force: true });
69
+ }
70
+ });
71
+
72
+ test("冲突时拒绝应用,且本地文件一个字节都不动", async () => {
73
+ const repo = initRepo();
74
+ try {
75
+ writeFileSync(join(repo, "a.txt"), "completely different\n", "utf8");
76
+ const result = await applyPatchToRepo({ repo, patch: Buffer.from(PATCH, "utf8"), dryRun: false });
77
+ assert.equal(result.ok, false);
78
+ assert.equal(result.ok === false && result.code, "E_APPLY_CONFLICT");
79
+ assert.equal(readFileSync(join(repo, "a.txt"), "utf8"), "completely different\n");
80
+ } finally {
81
+ rmSync(repo, { recursive: true, force: true });
82
+ }
83
+ });
84
+
85
+ test("空补丁与非仓库各自给出可识别错误", async () => {
86
+ const repo = initRepo();
87
+ const plain = mkdtempSync(join(tmpdir(), "pi-fabric-apply-plain-"));
88
+ try {
89
+ const empty = await applyPatchToRepo({ repo, patch: Buffer.alloc(0) });
90
+ assert.equal(empty.ok === false && empty.code, "E_PATCH_EMPTY");
91
+ const notRepo = await applyPatchToRepo({ repo: plain, patch: Buffer.from(PATCH, "utf8") });
92
+ assert.equal(notRepo.ok === false && notRepo.code, "E_NOT_A_REPO");
93
+ } finally {
94
+ rmSync(repo, { recursive: true, force: true });
95
+ rmSync(plain, { recursive: true, force: true });
96
+ }
97
+ });
98
+
99
+ test("dry-run 与真实应用都会给出「会改/已改哪些文件」", async () => {
100
+ const repo = initRepo();
101
+ try {
102
+ const patch = Buffer.from(PATCH, "utf8");
103
+ const dry = await applyPatchToRepo({ repo, patch });
104
+ assert.equal(dry.ok, true);
105
+ assert.deepEqual(dry.ok ? dry.files : [], ["a.txt"]);
106
+ assert.deepEqual(filesInPatch(patch), ["a.txt"]);
107
+
108
+ const applied = await applyPatchToRepo({ repo, patch, dryRun: false });
109
+ assert.equal(applied.ok, true);
110
+ assert.deepEqual(applied.ok ? applied.files : [], ["a.txt"]);
111
+ } finally {
112
+ rmSync(repo, { recursive: true, force: true });
113
+ }
114
+ });
115
+
@@ -0,0 +1,137 @@
1
+ /**
2
+ * 把远端任务的 diff 应用到本机仓库。
3
+ *
4
+ * 为什么不走 orchestrator_merge_back:那套是「同一台机器上的 worktree 合回本地分支」,
5
+ * 跨机场景下远端根本没有本地分支可合,唯一可靠的载体就是 patch。所以这里用
6
+ * git apply --3way,并且**先 --check 再真正应用**:宁可报冲突,也不留半套改动。
7
+ */
8
+ import { execFile } from "node:child_process";
9
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import { promisify } from "node:util";
13
+ import { cleanGitEnv, resolveRepoRoot } from "./fabric-worktree.ts";
14
+
15
+ const execFileAsync = promisify(execFile);
16
+
17
+ export interface ApplyPatchOptions {
18
+ repo: string;
19
+ patch: Buffer;
20
+ /** 只检查能不能干净应用,不写任何文件。默认 true(面板上要二次确认才真应用)。 */
21
+ dryRun?: boolean;
22
+ git?: string;
23
+ timeoutMs?: number;
24
+ log?: (message: string) => void;
25
+ }
26
+
27
+ export type ApplyPatchResult =
28
+ | { ok: true; dryRun: boolean; repo: string; message: string; files: string[] }
29
+ | { ok: false; code: string; message: string; files?: string[] };
30
+
31
+ /**
32
+ * 补丁会碰到哪些文件:直接读 `+++ b/<path>` 头。
33
+ * dry-run 时也要给人看「会改哪几个文件」,否则「能干净应用」这句话信息量为零。
34
+ */
35
+ export function filesInPatch(patch: Buffer): string[] {
36
+ const paths = new Set<string>();
37
+ for (const line of patch.toString("utf8").split("\n")) {
38
+ if (!line.startsWith("+++ b/")) continue;
39
+ const path = line.slice(6).trim();
40
+ if (path && path !== "/dev/null") paths.add(path);
41
+ }
42
+ return [...paths].slice(0, 200);
43
+ }
44
+
45
+ /** 应用后从 git status 读回真正变动的文件(比解析补丁更贴近事实)。 */
46
+ async function changedFiles(gitBin: string, repo: string, timeoutMs: number): Promise<string[]> {
47
+ try {
48
+ const { stdout } = await execFileAsync(gitBin, ["-C", repo, "status", "--porcelain"], {
49
+ timeout: timeoutMs,
50
+ maxBuffer: 8 * 1024 * 1024,
51
+ windowsHide: true,
52
+ env: cleanGitEnv(),
53
+ });
54
+ return String(stdout)
55
+ .split("\n")
56
+ .map((line) => line.slice(3).trim())
57
+ .filter((path) => path.length > 0)
58
+ .slice(0, 200);
59
+ } catch {
60
+ return [];
61
+ }
62
+ }
63
+
64
+ async function gitApply(
65
+ gitBin: string,
66
+ repo: string,
67
+ args: string[],
68
+ timeoutMs: number,
69
+ ): Promise<{ ok: true } | { ok: false; message: string }> {
70
+ try {
71
+ await execFileAsync(gitBin, ["-C", repo, "apply", ...args], {
72
+ timeout: timeoutMs,
73
+ maxBuffer: 8 * 1024 * 1024,
74
+ windowsHide: true,
75
+ env: cleanGitEnv(),
76
+ });
77
+ return { ok: true };
78
+ } catch (error) {
79
+ const stderr =
80
+ typeof error === "object" && error && "stderr" in error
81
+ ? String((error as { stderr?: unknown }).stderr ?? "")
82
+ : "";
83
+ return { ok: false, message: (stderr || (error instanceof Error ? error.message : String(error))).trim() };
84
+ }
85
+ }
86
+
87
+ export async function applyPatchToRepo(options: ApplyPatchOptions): Promise<ApplyPatchResult> {
88
+ const gitBin = options.git ?? "git";
89
+ const timeoutMs = options.timeoutMs ?? 60_000;
90
+ const dryRun = options.dryRun ?? true;
91
+ if (options.patch.length === 0) {
92
+ return { ok: false, code: "E_PATCH_EMPTY", message: "这个任务没有改动可应用" };
93
+ }
94
+ const repo = await resolveRepoRoot(options.repo, { git: gitBin });
95
+ if (!repo) {
96
+ return { ok: false, code: "E_NOT_A_REPO", message: `${options.repo} 不是 git 仓库` };
97
+ }
98
+ const work = mkdtempSync(join(tmpdir(), "pi-fabric-apply-"));
99
+ const patchFile = join(work, "change.patch");
100
+ try {
101
+ writeFileSync(patchFile, options.patch);
102
+ const args = ["--3way", "--whitespace=nowarn", patchFile];
103
+ // 先检查:git apply 失败可能已经改了一半文件,--check 通过才是真的能干净落地。
104
+ const check = await gitApply(gitBin, repo, ["--check", ...args], timeoutMs);
105
+ if (check.ok === false) {
106
+ options.log?.(`fabric apply check failed for ${repo}`);
107
+ return {
108
+ ok: false,
109
+ code: "E_APPLY_CONFLICT",
110
+ message: `补丁无法干净应用(本地可能已改过同一批文件):${check.message.slice(0, 500)}`,
111
+ files: filesInPatch(options.patch),
112
+ };
113
+ }
114
+ const touched = filesInPatch(options.patch);
115
+ if (dryRun) {
116
+ return { ok: true, dryRun: true, repo, message: "可以干净应用", files: touched };
117
+ }
118
+ const applied = await gitApply(gitBin, repo, args, timeoutMs);
119
+ if (applied.ok === false) {
120
+ return {
121
+ ok: false,
122
+ code: "E_APPLY_FAILED",
123
+ message: `应用补丁失败:${applied.message.slice(0, 500)}`,
124
+ };
125
+ }
126
+ const statusFiles = await changedFiles(gitBin, repo, timeoutMs);
127
+ return {
128
+ ok: true,
129
+ dryRun: false,
130
+ repo,
131
+ message: "已应用到本地仓库,改动未提交",
132
+ files: statusFiles.length > 0 ? statusFiles : touched,
133
+ };
134
+ } finally {
135
+ rmSync(work, { recursive: true, force: true });
136
+ }
137
+ }
@@ -0,0 +1,51 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import {
4
+ AVATAR_COLS,
5
+ AVATAR_ROWS,
6
+ avatarEquals,
7
+ avatarForNodeId,
8
+ shortNodeId,
9
+ } from "../../../contract/fabric-avatar.ts";
10
+
11
+ test("同一 nodeId 永远画出同一张脸,不同 nodeId 画不同的脸", () => {
12
+ const a = avatarForNodeId("0123456789abcdef");
13
+ const same = avatarForNodeId("0123456789abcdef");
14
+ const other = avatarForNodeId("fedcba9876543210");
15
+ assert.deepEqual(a, same);
16
+ assert.equal(avatarEquals(a, other), false);
17
+ assert.equal(avatarEquals(a, same), true);
18
+ });
19
+
20
+ test("图形左右对称,格数固定 25", () => {
21
+ const avatar = avatarForNodeId("deadbeefdeadbeef");
22
+ assert.equal(avatar.cells.length, AVATAR_COLS * AVATAR_ROWS);
23
+ for (let row = 0; row < AVATAR_ROWS; row += 1) {
24
+ for (let col = 0; col < AVATAR_COLS; col += 1) {
25
+ assert.equal(
26
+ avatar.cells[row * AVATAR_COLS + col],
27
+ avatar.cells[row * AVATAR_COLS + (AVATAR_COLS - 1 - col)],
28
+ );
29
+ }
30
+ }
31
+ });
32
+
33
+ test("色相落在 0–359,短 ID 取前 4 位,脏输入不炸", () => {
34
+ for (const id of ["0123456789abcdef", "zzzz", "", "ABCDEF"]) {
35
+ const avatar = avatarForNodeId(id);
36
+ assert.ok(avatar.hue >= 0 && avatar.hue < 360);
37
+ assert.equal(avatar.shortId, shortNodeId(id));
38
+ }
39
+ });
40
+
41
+ test("抽 200 个 nodeId 不撞脸(图 + 色相一起比)", () => {
42
+ const seen = new Map<string, string>();
43
+ for (let index = 0; index < 200; index += 1) {
44
+ const nodeId = index.toString(16).padStart(16, "0");
45
+ const avatar = avatarForNodeId(nodeId);
46
+ const key = `${avatar.hue}:${avatar.cells.map((cell) => (cell ? "1" : "0")).join("")}`;
47
+ const clash = seen.get(key);
48
+ assert.equal(clash, undefined, `${nodeId} 与 ${clash} 撞脸`);
49
+ seen.set(key, nodeId);
50
+ }
51
+ });
@@ -0,0 +1,100 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createSocket } from "node:dgram";
4
+ import { FABRIC_PROTOCOL_VERSION } from "../../../contract/domains/fabric.ts";
5
+ import { broadcastAddresses, scanLan, startAnnouncer, startResponder } from "./discovery.ts";
6
+
7
+ /** 用裸 UDP 打一发探测包:用来验证「协议不合时对方不回应答」这条边界。 */
8
+ async function rawProbe(port: number, payload: string, waitMs = 400): Promise<string[]> {
9
+ const socket = createSocket("udp4");
10
+ const replies: string[] = [];
11
+ socket.on("message", (data) => replies.push(data.toString("utf8")));
12
+ await new Promise<void>((resolve) => socket.bind(0, "127.0.0.1", () => resolve()));
13
+ socket.send(Buffer.from(payload, "utf8"), port, "127.0.0.1");
14
+ await new Promise<void>((resolve) => setTimeout(resolve, waitMs));
15
+ await new Promise<void>((resolve) => socket.close(() => resolve()));
16
+ return replies;
17
+ }
18
+
19
+ test("广播地址至少含全局广播与回环(同机双实例也要能发现)", () => {
20
+ const targets = broadcastAddresses();
21
+ assert.ok(targets.includes("255.255.255.255"));
22
+ assert.ok(targets.includes("127.0.0.1"));
23
+ });
24
+
25
+ test("应答线程:扫得到自己,回包带 nodeId / 端口 / 版本", async () => {
26
+ const announcer = await startAnnouncer({
27
+ nodeId: "0123456789abcdef",
28
+ tcpPort: 7788,
29
+ appVersion: "0.12.1",
30
+ port: 0,
31
+ });
32
+ try {
33
+ const devices = await scanLan({ port: announcer.port, timeoutMs: 900 });
34
+ const self = devices.find((device) => device.nodeId === "0123456789abcdef");
35
+ assert.ok(self, "扫描结果里应该有自己");
36
+ assert.equal(self?.tcpPort, 7788);
37
+ assert.equal(self?.shortId, "0123");
38
+ assert.equal(self?.appVersion, "0.12.1");
39
+ assert.equal(self?.protocolVersion, FABRIC_PROTOCOL_VERSION);
40
+ } finally {
41
+ await announcer.close();
42
+ }
43
+ });
44
+
45
+ test("协议版本不合的探测不被应答,但必须留下日志(拒绝不能静默)", async () => {
46
+ const logs: string[] = [];
47
+ // 显式钉一个远离真机端口的探测口:测试不该受本机正在跑的 PiForge / 其它实例影响。
48
+ const responder = await startResponder({
49
+ nodeName: "PC-GATE",
50
+ tcpPort: 7788,
51
+ ctx: "piforge",
52
+ base: 8_500 + (process.pid % 100),
53
+ span: 1,
54
+ log: (message) => logs.push(message),
55
+ });
56
+ try {
57
+ const replies = await rawProbe(responder.port, "SBF1|piforge|PC-GATE|99");
58
+ assert.deepEqual(replies, [], "版本不合时不该回 SBF2");
59
+ assert.ok(
60
+ logs.some((line) => line.includes("协议")),
61
+ `应记录拒绝原因,实际日志:${logs.join(" / ") || "(空)"}`,
62
+ );
63
+ } finally {
64
+ await responder.close();
65
+ }
66
+ });
67
+
68
+ test("扫描忽略协议版本不合的 SBF4 回包", async () => {
69
+ const fake = createSocket("udp4");
70
+ await new Promise<void>((resolve) => fake.bind(0, "127.0.0.1", () => resolve()));
71
+ const port = (fake.address() as { port: number }).port;
72
+ fake.on("message", (_data, from) => {
73
+ fake.send(Buffer.from("SBF4|0123456789abcdef|7788|99|0.0.1", "utf8"), from.port, from.address);
74
+ });
75
+ try {
76
+ const devices = await scanLan({ port, timeoutMs: 500 });
77
+ assert.equal(
78
+ devices.find((device) => device.nodeId === "0123456789abcdef"),
79
+ undefined,
80
+ "协议不合的机器不该出现在可配对列表里",
81
+ );
82
+ } finally {
83
+ await new Promise<void>((resolve) => fake.close(() => resolve()));
84
+ }
85
+ });
86
+
87
+ test("关掉「允许局域网发现」后不再应答,扫描为空数组", async () => {
88
+ const announcer = await startAnnouncer({
89
+ nodeId: "fedcba9876543210",
90
+ tcpPort: 7788,
91
+ enabled: () => false,
92
+ port: 0,
93
+ });
94
+ try {
95
+ const devices = await scanLan({ port: announcer.port, timeoutMs: 700 });
96
+ assert.equal(devices.length, 0);
97
+ } finally {
98
+ await announcer.close();
99
+ }
100
+ });
@@ -0,0 +1,68 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { FabricHistory, HISTORY_SAMPLES, historyKey, historyPath } from "./history.ts";
7
+
8
+ function tempDir(): { dir: string; cleanup: () => void } {
9
+ const dir = mkdtempSync(join(tmpdir(), "pi-fabric-history-"));
10
+ return { dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
11
+ }
12
+
13
+ test("标签键与顺序无关,空标签归到一个桶", () => {
14
+ assert.equal(historyKey(["gpu", "build"]), historyKey(["build", "gpu"]));
15
+ assert.equal(historyKey([]), "*");
16
+ assert.equal(historyKey([" Build ", "build"]), "build");
17
+ });
18
+
19
+ test("中位耗时:奇数取中间,偶数取两者均值", () => {
20
+ const { dir, cleanup } = tempDir();
21
+ try {
22
+ const history = new FabricHistory(dir);
23
+ for (const ms of [10_000, 30_000, 20_000]) history.record(["build"], ms, true, 1);
24
+ assert.equal(history.p50(["build"]), 20_000);
25
+ history.record(["build"], 60_000, true, 2);
26
+ assert.equal(history.p50(["build"]), 25_000);
27
+ assert.equal(history.p50(["gpu"]), null);
28
+ } finally {
29
+ cleanup();
30
+ }
31
+ });
32
+
33
+ test("样本数有上限,不会无限长", () => {
34
+ const { dir, cleanup } = tempDir();
35
+ try {
36
+ const history = new FabricHistory(dir);
37
+ for (let index = 0; index < HISTORY_SAMPLES + 10; index += 1) history.record(["build"], index, true, index);
38
+ const entry = history.snapshot()["build"];
39
+ assert.equal(entry?.samples.length, HISTORY_SAMPLES);
40
+ } finally {
41
+ cleanup();
42
+ }
43
+ });
44
+
45
+ test("文件坏掉当作没历史,不抛", () => {
46
+ const { dir, cleanup } = tempDir();
47
+ try {
48
+ const file = historyPath(dir);
49
+ mkdirSync(join(dir, "fabric"), { recursive: true });
50
+ writeFileSync(file, "{not json", "utf8");
51
+ const history = new FabricHistory(dir);
52
+ assert.equal(history.p50(["build"]), null);
53
+ history.record(["build"], 1_000, true, 1);
54
+ assert.equal(history.p50(["build"]), 1_000);
55
+ } finally {
56
+ cleanup();
57
+ }
58
+ });
59
+
60
+ test("落盘后新实例能读到(跨重启可用)", () => {
61
+ const { dir, cleanup } = tempDir();
62
+ try {
63
+ new FabricHistory(dir).record(["build"], 42_000, true, 1);
64
+ assert.equal(new FabricHistory(dir).p50(["build"]), 42_000);
65
+ } finally {
66
+ cleanup();
67
+ }
68
+ });
@@ -0,0 +1,112 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtempSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { FabricService } from "./fabric-service.ts";
7
+
8
+ function tempDir(): { dir: string; cleanup: () => void } {
9
+ const dir = mkdtempSync(join(tmpdir(), "pi-fabric-keepalive-"));
10
+ return { dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
11
+ }
12
+
13
+ function pairBoth(a: FabricService, b: FabricService) {
14
+ const first = a.pair({
15
+ nodeId: b.nodeId,
16
+ publicKey: b.identity.publicKey,
17
+ name: "机-B",
18
+ address: "127.0.0.1",
19
+ port: b.port,
20
+ grants: "workspace-rw+bash",
21
+ });
22
+ const second = b.pair({
23
+ nodeId: a.nodeId,
24
+ publicKey: a.identity.publicKey,
25
+ name: "机-A",
26
+ address: "127.0.0.1",
27
+ port: a.port,
28
+ grants: "workspace-rw+bash",
29
+ });
30
+ assert.equal(first.ok, true);
31
+ assert.equal(second.ok, true);
32
+ }
33
+
34
+ test("配对即建常驻连接:两侧自动变成 online,不需要先派活", async () => {
35
+ const a = tempDir();
36
+ const b = tempDir();
37
+ const svcA = new FabricService({ agentDir: a.dir, host: "127.0.0.1", port: 0, ctx: `ka-a-${process.pid}` });
38
+ const svcB = new FabricService({ agentDir: b.dir, host: "127.0.0.1", port: 0, ctx: `ka-b-${process.pid}` });
39
+ try {
40
+ await svcA.start();
41
+ await svcB.start();
42
+ pairBoth(svcA, svcB);
43
+ await waitFor(() => svcA.connectionStates()[svcB.nodeId] === "online", 5_000);
44
+ await waitFor(() => svcB.connectionStates()[svcA.nodeId] === "online", 5_000);
45
+ } finally {
46
+ await svcA.stop();
47
+ await svcB.stop();
48
+ a.cleanup();
49
+ b.cleanup();
50
+ }
51
+ });
52
+
53
+ test("对端重启后连接自己回到 online(不手动取消就一直连)", async () => {
54
+ const a = tempDir();
55
+ const b = tempDir();
56
+ const svcA = new FabricService({ agentDir: a.dir, host: "127.0.0.1", port: 0, ctx: `ka-c-${process.pid}` });
57
+ let svcB = new FabricService({ agentDir: b.dir, host: "127.0.0.1", port: 0, ctx: `ka-d-${process.pid}` });
58
+ try {
59
+ await svcA.start();
60
+ await svcB.start();
61
+ pairBoth(svcA, svcB);
62
+ await waitFor(() => svcA.connectionStates()[svcB.nodeId] === "online", 5_000);
63
+
64
+ const portB = svcB.port;
65
+ await svcB.stop();
66
+ await waitFor(() => svcA.connectionStates()[svcB.nodeId] === "reconnecting", 10_000);
67
+
68
+ svcB = new FabricService({
69
+ agentDir: b.dir,
70
+ host: "127.0.0.1",
71
+ port: portB,
72
+ ctx: `ka-d-${process.pid}`,
73
+ });
74
+ await svcB.start();
75
+ await waitFor(() => svcA.connectionStates()[svcB.nodeId] === "online", 15_000);
76
+ } finally {
77
+ await svcA.stop();
78
+ await svcB.stop();
79
+ a.cleanup();
80
+ b.cleanup();
81
+ }
82
+ });
83
+
84
+ test("取消配对是唯一主动断开的路径", async () => {
85
+ const a = tempDir();
86
+ const b = tempDir();
87
+ const svcA = new FabricService({ agentDir: a.dir, host: "127.0.0.1", port: 0, ctx: `ka-e-${process.pid}` });
88
+ const svcB = new FabricService({ agentDir: b.dir, host: "127.0.0.1", port: 0, ctx: `ka-f-${process.pid}` });
89
+ try {
90
+ await svcA.start();
91
+ await svcB.start();
92
+ pairBoth(svcA, svcB);
93
+ await waitFor(() => svcA.connectionStates()[svcB.nodeId] === "online", 5_000);
94
+
95
+ assert.equal(svcA.unpair(svcB.nodeId), true);
96
+ assert.equal(svcA.connectionStates()[svcB.nodeId], undefined);
97
+ assert.deepEqual(svcA.snapshot().peers, []);
98
+ } finally {
99
+ await svcA.stop();
100
+ await svcB.stop();
101
+ a.cleanup();
102
+ b.cleanup();
103
+ }
104
+ });
105
+
106
+ async function waitFor(predicate: () => boolean, timeoutMs: number): Promise<void> {
107
+ const startedAt = Date.now();
108
+ while (!predicate()) {
109
+ if (Date.now() - startedAt > timeoutMs) throw new Error("condition not met in time");
110
+ await new Promise((resolve) => setTimeout(resolve, 25));
111
+ }
112
+ }